Handler, http.Handle, http.HandlerFunc, http.HandleFunc, http.ServeMux, http.ListenAndServe
Handler
觀察 Handler 的參數之後會發現有一個 ResponseWriter 與一個 *Request,
這就對應到 Client 與 Server 之間的互動,
當 Client 發送 Request 給 Server 的時候, Handler 就會被呼叫,
並且把回應用 ResponseWriter 回傳給 Client.
ServeHTTP(w http.ResponseWriter, req *http.Request)
任何有長成這樣的都是 Handler 😸
http.Handle
func Handle(pattern string, handler Handler)
http.Handle 會幫我們註冊哪個 pattern 要使用哪一個 Handler.
http.HandlerFunc
type HandlerFunc func(ResponseWriter, *Request)// ServeHTTP calls f(w, r).
func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) { f(w, r)}
只要把長成以下這樣的 function 丟進去給 http.HandlerFunc
func myHandlerFunction(w http.ResponseWriter, req *http.Request) {
// Do Something
}
就能夠拿到一個擁有 ServeHTTP 的物件, 也就能被當作是 Handler 來使用.
http.HandleFunc
// HandleFunc registers the handler function for the given pattern
// in the DefaultServeMux.
// The documentation for ServeMux explains how patterns are matched.func HandleFunc(
pattern string,
handler func(ResponseWriter, *Request)
) {
DefaultServeMux.HandleFunc(pattern, handler)
}
// HandleFunc registers the handler function for the given pattern.func (mux *ServeMux) HandleFunc(
pattern string,
handler func(ResponseWriter, *Request)
) {
mux.Handle(pattern, HandlerFunc(handler))
}
可以看到 http.HandleFunc 會把傳進來的 function 轉換成 handler,
並且為這個 pattern 註冊此 handler.
http.ServeMux
Server 會依照 Client 傳來的 Url 以及 Method 來決定要啟動哪個 Handler,
這時候就得靠 http.ServeMux 來做到這件事情.
例如 :
(url, method) = (‘/user/’, ‘GET’)
(url, method) = (‘/user/’, ‘POST’)
// Handle registers the handler for the given pattern.
// If a handler already exists for pattern, Handle panics.func (mux *ServeMux) Handle(pattern string, handler Handler)
http.ListenAndServe
func ListenAndServe(addr string, handler Handler)
http.ListenAndServe 會去監聽 TCP network 的 addr 這個接口,
並且呼叫 handler 來處理傳入的 requests,
這邊的 handler 一般來說會給 nil, 使用預設的 DefaultServeMux.