Go by Example:HTTP Server

使用 net/http 套件撰寫基本的 HTTP Server 非常容易。

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

net/http Server 的一個基本概念是 處理常式。處理常式是一個實作 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)

最後,我們呼叫 ListenAndServe 並指定連接埠和處理常式。nil 會指示它使用我們剛剛設定好的預設路由器。

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

在背景中執行伺服器。

$ go run http-servers.go &

取得 /hello 路徑。

$ curl localhost:8090/hello
hello

下一範例:Context