Go http.ServeMux簡介。
簡介
Mux這個字為multiplexer的縮寫,稱為「數據多工器/多路復用器」,用途為從多個輸入訊號中選擇其一並輸出的元件。ServeMux則為處理多個HTTP請求的「多工器」,作用為匹配請求的URL與註冊的URL pattern並分派至handler處理,又稱為router或dispatcher。
方法
ServeMux.Handle
ServeMux.Handle(pattern string, handler Handler)方法用來註冊URL pattern及處理請求的handler。
ServeMux.HandleFunc
ServeMux.HandleFunc(pattern string, handler func(ResponseWriter, *Request)方法則是註冊URL pattern及處理請求的handler函式。
ServeMux.ServeHTTP
ServeMux.ServeHTTP(w ResponseWriter, r *Request)實現了http.Handler介面的ServeHTTP(ResponseWriter, *Request),所以本身即為http.Handler,作用為http.Server建立HTTP連線時呼叫。
下面為使用ServeMux處理請求的簡單範例。
範例環境:
- Go 1.18
範例
使用http.NewServeMux()建立新的http.ServeMux實例。接著調用http.ServeMux.Handle()註冊URL pattern及處理請求的handler。handler型態為http.Handler介面,所以必須實作ServeHTTP(ResponseWriter, *Request)。
建立一個函式型別HelloHandler實作ServeHTTP(ResponseWriter, *Request)因此HelloHandler屬於http.Handler,又HelloHandler簽章為(ResponseWriter, *Request)所以在HelloHandler.ServeHTTP(ResponseWriter, *Request)實作中能調用本身(此為讓客戶端自行定義介面方法實作的手法)。
建立一個HellohandlerFunc函式為HelloHandler的實例。為實際處理匹配/hello請求的函式。
註解起來的mux.HandleFunc("/hello", HellohandlerFunc)作用同上,但同一pattern不能重複註冊否則啟動時會出現錯誤。ServeMux.HandleFunc()為ServeMux.Handle()的一層包裝,內部利用內建的http.HandlerFunc建立handler。
最後將ServeMux實例傳入http.ListenAndServe(addr string, handler Handler)作為http.Server處理請求的handler。
main.go
package main
import (
"net/http"
)
func main() {
mux := http.NewServeMux()
h := HelloHandler(HellohandlerFunc)
mux.Handle("/hello", h)
// mux.HandleFunc("/hello", HellohandlerFunc)
http.ListenAndServe(":8080", mux)
}
type HelloHandler func(w http.ResponseWriter, r *http.Request)
func (f HelloHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
f(w, r)
}
func HellohandlerFunc(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("hello"))
}
一般多直接呼叫http.Handle(pattern string, handler Handler)或http.HandleFunc(pattern string, handler func(ResponseWriter, *Request))設定pattern及handler,其使用的ServeMux為內建的http.DefaultServeMux。
測試
啟動專案並在命令列以curl發出curl -X GET "http://localhost:8080/hello"的回應如下。
$ curl "http://localhost:8080/hello"
hello
沒有留言:
張貼留言