Go 語言的網路編程簡介

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

本文通過 Go 語言寫幾個簡單的通訊樣本,從 TCP 伺服器過渡到 HTTP 開發,從而簡單介紹 net 包的運用。

TCP 伺服器

首先來看一個 TCP 伺服器例子

package mainimport (    "fmt"    "log"    "net")func main() {    // net 包提供方便的工具用於 network I/O 開發,包括TCP/IP, UDP 協議等。    // Listen 函數會監聽來自 8080 連接埠的串連,返回一個 net.Listener 對象。    li, err := net.Listen("tcp", ":8080")    // 錯誤處理    if err != nil {        log.Panic(err)    }    // 釋放串連,通過 defer 關鍵字可以讓串連在函數結束前進行釋放    // 這樣可以不關心釋放資源的語句位置,增加代碼可讀性    defer li.Close()    // 不斷迴圈,不斷接收來自用戶端的請求    for {        // Accept 函數會阻塞程式,直到接收到來自連接埠的串連        // 每接收到一個連結,就會返回一個 net.Conn 對象表示這個串連        conn, err := li.Accept()        if err != nil {            log.Println(err)        }        // 字串寫入到用戶端        fmt.Fprintln(conn, "Hello from TCP server")        conn.Close()    }}

在對應的檔案夾下啟動伺服器

$ go run main.go

類比用戶端程式發出請求,這裡使用 netcat 工具,也就是 nc 命令。

$ nc localhost 8080Hello from TCP server

通過 net 包,我們可以很簡單的去寫一個 TCP 伺服器,代碼可讀性強。

TCP 用戶端

那麼我們能不能用 Go 語言來類比用戶端,從而串連前面的伺服器呢?答案是肯定的。

package mainimport (    "fmt"    "io/ioutil"    "log"    "net")func main() {    // net 包的 Dial 函數能建立一個 TCP 串連    conn, err := net.Dial("tcp", ":8080")    if err != nil {        log.Fatal(err)    }    // 別忘了關閉串連    defer conn.Close()    // 通過 ioutil 來讀取串連中的內容,返回一個 []byte 類型的對象    byte, err := ioutil.ReadAll(conn)    if err != nil {        log.Println(err)    }    // []byte 類型的資料轉成字串型,再將其列印輸出    fmt.Println(string(byte))}

運行伺服器後,再在所在的檔案夾下啟動用戶端,會看到來自伺服器的問候。

$ go run main.goHello from TCP server

TCP 協議類比 HTTP 要求

我們知道 TCP/IP 協議是傳輸層協議,主要解決的是資料如何在網路中傳輸。而 HTTP 是應用程式層協議,主要解決的是如何封裝這些資料。

下面的七層網路通訊協定圖也能看到 HTTP 層是處於 TCP 層之上的,能對來自 TCP 層的資料進行封裝,再展現到我們面前。


七層網路通訊協定圖

現在我們寫一個基於 TCP 協議的伺服器,並能類比。在這其中,我們需要類比發送 HTTP 回應標頭資訊,我們可以用 curl -i 命令先來查看一下其他網站的回應標頭資訊。

$ curl -i "www.baidu.com"HTTP/1.1 200 OK  # HTTP 協議及請求碼Server: bfe/1.0.8.18    # 伺服器使用的WEB軟體名及版本Date: Sat, 29 Apr 2017 07:30:33 GMT  # 發送時間Content-Type: text/html   # 內容類型Content-Length: 277            # 內容長度Last-Modified: Mon, 13 Jun 2016 02:50:23 GMT...  # balabalaAccept-Ranges: bytes<!DOCTYPE html>  # 訊息體<!--STATUS OK--><html>...</body> </html>

接下來,我們嘗試寫出能輸出對應格式響應內容的伺服器。

package mainimport (    "fmt"    "log"    "net")func main() {    li, err := net.Listen("tcp", ":8080")    if err != nil {        log.Fatalln(err.Error())    }    defer li.Close()    for {        conn, err := li.Accept()        if err != nil {            log.Fatalln(err.Error())            continue        }        // 函數前添加 go 關鍵字,就能使其擁有 Go 語言的並發功能        // 這樣我們可以同時處理來自不同用戶端的請求        go handle(conn)    }}func handle(conn net.Conn) {    defer conn.Close()    // 回應用戶端的請求    respond(conn)}func respond(conn net.Conn) {    // 訊息體    body := `<!DOCTYPE html><html lang="en"><head><meta charet="UTF-8"><title>Go example</title></head><body><strong>Hello World</strong></body></html>`    // HTTP 協議及請求碼    fmt.Fprint(conn, "HTTP/1.1 200 OK\r\n")    // 內容長度    fmt.Fprintf(conn, "Content-Length: %d\r\n", len(body))     // 內容類型    fmt.Fprint(conn, "Content-Type: text/html\r\n")    fmt.Fprint(conn, "\r\n")    fmt.Fprint(conn, body)}

go run main.go 啟動伺服器之後,跳轉到 localhost:8080,就能看到網頁內容,並且用開發人員工具能看到其要求標頭。


最簡單的 HTTP 伺服器

幾行代碼就能實現一個最簡單的 HTTP 伺服器。

package mainimport "net/http"func main() {    http.ListenAndServe(":8080", nil)}

開啟後會發現顯示「404 page not found」,這說明 HTTP 已經開始服務了!

ListenAndServe

Go 是通過一個函數 ListenAndServe 來處理這些事情的,這個底層其實這樣處理的:初始化一個server 對象,然後調用了 net.Listen("tcp", addr),也就是底層用 TCP 協議搭建了一個服務,然後監控我們設定的連接埠。
《Build web application with golang》, astaxie

前面我們已經對 TCP 伺服器有點熟悉了,接下來看看如何用 net/http 包來實現在其上的 HTTP 協議。

查文檔可以發現 http 包下的 ListenAndServe 函數第一個參數是地址,而第二個是 Handler 類型的參數,我們想要顯示內容就要在第二個參數下功夫。

func ListenAndServe(addr string, handler Handler) error

再次查文檔,得知 Handler 是一個介面,也就是說只要我們給某一個類型建立 ServeHTTP(ResponseWriter, *Request) 方法,就能符合介面的要求,也就實現了介面。

type Handler interface {        ServeHTTP(ResponseWriter, *Request)}
package mainimport (    "fmt"    "net/http")// 建立一個 foo 類型type foo struct {}// 為 foo 類型建立 ServeHTTP 方法,以實現 Handle 介面func (f foo) ServeHTTP(w http.ResponseWriter, r *http.Request) {    fmt.Fprintln(w, "Implement the Handle interface.")}func main() {    // 建立對象,類型名寫後面..    var f foo    http.ListenAndServe(":8080",f)}

運行代碼後開啟能看到輸出的字串。


*http.Request

上面我們實現的小伺服器裡,我們無論訪問 localhost:8080 還是 localhost:8080/foo 都是一樣的頁面,這說明我們之前設定的是預設的頁面,還沒有為特定的路由(route)設定內容。

路由這些資訊實際上就存在 ServeHTTP 函數的第二個參數 *http.Request 中, *http.Request 存放著用戶端發送至伺服器的請求資訊,例如請求連結、要求方法、回應標頭、訊息體等等。

現在我們可以把上面的代碼改造一下。

package mainimport (    "fmt"    "net/http")// 建立一個 foo 類型type foo struct {}// 為 foo 類型建立 ServeHTTP 方法,以實現 Handle 介面func (f foo) ServeHTTP(w http.ResponseWriter, r *http.Request) {    // 根據 URL 的相對路徑來設定網頁內容(不優雅)    switch r.URL.Path {    case "/boy":        fmt.Fprintln(w, "I love you!!!")    case "/girl":        fmt.Fprintln(w, "hehe.")    default:        fmt.Fprintln(w, "Men would stop talking and women would shed tears when they see this.")}func main() {    // 建立對象,類型名寫後面..    var f foo    http.ListenAndServe(":8080",f)}

再優雅一點

我們可以用 HTTP 要求多工器(HTTP request multiplexer) 來實現分發路由,而http.NewServeMux() 返回的 *ServeMux 對象就能實現這樣的功能。下面是 *ServeMux 的部分源碼,能看到通過 *ServeMux 就能為每一個路由設定單獨的一個 handler 了,簡單地說就是不同的內容。

type ServeMux struct {    mu    sync.RWMutex         // 讀寫鎖    m     map[string]muxEntry  // 路由資訊(索引值對)    hosts bool                 // 是否包含 hostnames}type muxEntry struct {    explicit bool     // 是否精確匹配    h        Handler  // muxEntry.Handler 是介面    pattern  string   // 路由}type Handler interface {    ServeHTTP(ResponseWriter, *Request)}

用 *ServeMux 來寫一個例子。

package mainimport (    "fmt"    "net/http")type boy struct{}func (b boy) ServeHTTP(w http.ResponseWriter, r *http.Request) {    fmt.Fprintln(w, "I love you!!!")}type girl struct{}func (g girl) ServeHTTP(w http.ResponseWriter, r *http.Request) {    fmt.Fprintln(w, "hehe.")}type foo struct{}func (f foo) ServeHTTP(w http.ResponseWriter, r *http.Request) {    fmt.Fprintln(w, "Men would stop talking and women would shed tears when they see this.")}func main() {    var b boy    var g girl    var f foo    // 返回一個 *ServeMux 對象    mux := http.NewServeMux()      mux.Handle("/boy/", b)    mux.Handle("/girl/", g)    mux.Handle("/", f)    http.ListenAndServe(":8080", mux)}

這樣就能為每一個路由設定單獨的頁面了。

再再優雅一點

http.Handle(pattern string, handler Handler) 還能幫我們簡化代碼,它預設建立一個 DefaultServeMux,也就是預設的 ServeMux 來存 handler 資訊,這樣就不需要 http.NewServeMux() 函數了。這看起來雖然沒有什麼少寫多少代碼,但是這是下一個更加優雅方法的轉折點。

package mainimport (    "fmt"    "net/http")type boy struct{}func (b boy) ServeHTTP(w http.ResponseWriter, r *http.Request) {    fmt.Fprintln(w, "I love you!!!")}type girl struct{}func (g girl) ServeHTTP(w http.ResponseWriter, r *http.Request) {    fmt.Fprintln(w, "hehe.")}type foo struct{}func (f foo) ServeHTTP(w http.ResponseWriter, r *http.Request) {    fmt.Fprintln(w, "Men would stop talking and women would shed tears when they see this.")}func main() {    var b boy    var g girl    var f foo    http.Handle("/boy/", b)    http.Handle("/girl/", g)    http.Handle("/", f)    http.ListenAndServe(":8080", nil)}

再再再優雅一點

http.HandleFunc(pattern string, handler func(ResponseWriter, *Request)) 可以看做 http.Handle(pattern string, handler Handler) 的一種封裝。前者的第二個參數變成了一個函數,這樣我們就不用多次建立對象,再為對象實現 ServeHTTP() 方法來實現不同的 handler 了。下面是 http.HandleFun() 的部分源碼。

func HandleFunc(pattern string, handler func(ResponseWriter, *Request)) {    // 同樣利用 DefaultServeMux 來存路由資訊    DefaultServeMux.HandleFunc(pattern, handler)}func (mux *ServeMux) HandleFunc(pattern string, handler func(ResponseWriter, *Request)) {    // 是不是似曾相識?    mux.Handle(pattern, HandlerFunc(handler))}

用 http.HandleFun() 來重寫之前的例子。

package mainimport (    "fmt"    "net/http")func boy(w http.ResponseWriter, r *http.Request) {    fmt.Fprintln(w, "I love you!!!")}func girl(w http.ResponseWriter, r *http.Request) {    fmt.Fprintln(w, "hehe.")}func foo(w http.ResponseWriter, r *http.Request) {    fmt.Fprintln(w, "Men would stop talking and women would shed tears when they see this.")}func main() {    http.HandleFunc("/boy/", boy)    http.HandleFunc("/girl/", girl)    http.HandleFunc("/", foo)    http.ListenAndServe(":8080", nil)}

HandlerFunc

另外,http 包裡面還定義了一個類型 http.HandlerFunc,該類型預設實現 Handler 介面,我們可以通過 HandlerFunc(foo) 的方式來實作類別型強轉,使 foo 也實現了 Handler 介面。

type HandlerFunc func(ResponseWriter, *Request)// 實現 Handler 介面func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) {    f(w, r)}
package mainimport (    "fmt"    "net/http")func boy(w http.ResponseWriter, r *http.Request) {    fmt.Fprintln(w, "I love you!!!")}func girl(w http.ResponseWriter, r *http.Request) {    fmt.Fprintln(w, "hehe.")}func foo(w http.ResponseWriter, r *http.Request) {    fmt.Fprintln(w, "Men would stop talking and women would shed tears when they see this.")}func main() {    // http.Handler() 的第二個參數是要實現了 Handler 介面的類型    // 可以通過類型強轉來重新使用該函數來實現    http.Handle("/boy/", http.HandlerFunc(boy))    http.Handle("/girl/", http.HandlerFunc(girl))    http.Handle("/", http.HandlerFunc(foo))    http.ListenAndServe(":8080", nil)}

結尾

本文從搭建 TCP 伺服器一步步到搭建 HTTP 伺服器,展示了 Go 語言網路程式庫的強大,我認為 Go 語言是熟悉網路通訊協定的一個很好的工具。自己從熟悉了擁有各種 feature 的 Swift 語言之後再入門到看似平凡無奇的 Go 語言,經曆了從為語言的平庸感到驚訝不解到為其遵循規範和良好的工業語言設計而感到驚歎和興奮的轉變。

最後希望本文能為有基礎的同學理清思路,也能吸引更多同學來學習這門優秀的語言。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.