以示例學習:HTTP 伺服器

使用 net/http 套件撰寫基本的 HTTP 伺服器很簡單。

package main
import (
    "fmt"
    "net/http"
)

net/http 伺服器中一個基本概念是 _處理常式_。處理常式是實作 http.Handler 介面的物件。撰寫處理常式的常見方法是對具有適當簽章的函式使用 http.HandlerFunc 適配器。

func hello(w http.ResponseWriter, req *http.Request) {

用作處理常式的函式以 http.ResponseWriterhttp.Request 作為引數。回應撰寫器用於填入 HTTP 回應。在此,我們簡單的回應只是「hello\n」。

    fmt.Fprintf(w, "hello\n")
}
func headers(w http.ResponseWriter, req *http.Request) {

這個處理常式會執行更精密的動作,讀取所有 HTTP 請求標頭並將它們呼應到回應本文中。

    for name, headers := range req.Header {
        for _, h := range headers {
            fmt.Fprintf(w, "%v: %v\n", name, h)
        }
    }
}
func main() {

我們使用 http.HandleFunc 簡易函式在伺服器路由上註冊我們的處理常式。它設定 net/http 套件中的 _預設路由器_ 並以函式作為引數。

    http.HandleFunc("/hello", hello)
    http.HandleFunc("/headers", headers)

最後,我們以連接埠和處理常式呼叫 ListenAndServenil 告訴它使用我們剛剛設定的預設路由器。

    http.ListenAndServe(":8090", nil)
}

在背景中執行伺服器。

$ go run http-servers.go &

存取 /hello 路由。

$ curl localhost:8090/hello
hello

下一個範例:Context