這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
Keywords: HandlerFunc, ServeHTTP, NotFoundHandler
前言
在Go-HTTP中,已經介紹了HandlerFunc。為了查閱方便,單獨再拎出來講一講。
原始代碼
定義在server.go檔案中,如下。
// The HandlerFunc type is an adapter to allow the use of// ordinary functions as HTTP handlers. If f is a function// with the appropriate signature, HandlerFunc(f) is a// Handler that calls f.type HandlerFunc func(ResponseWriter, *Request)// ServeHTTP calls f(w, r).func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) { f(w, r)}
功能
HandlerFunc是一種資料類型,或者嚴格地講,是函數類型。不管怎麼說,HandlerFunc是一種type是無疑問的。而且,這個HandlerFunc實現了Handler介面的ServerHttp方法,所以HandlerFunc是Handler的具體類。
慣用法
習慣上,先定義自己的符合如下前面的函數:
func(ResponseWriter, *Request)
然後通過“類型轉換”,將該函數轉換成HandlerFunc類型,從而就變成了Handler對象。
樣本
在Go-HTTP一文,給出了相關的範例程式碼,再次拷貝過來(msgHandler):
package main import ( "fmt" "log" "net/http")func msgHandler(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "Hello, HandlerFunc!")}func main() { mux := http.NewServeMux() handler := http.HandlerFunc(msgHandler) mux.Handle("/hello", handler) log.Println("Listening...") http.ListenAndServe(":8080", mux)}
NotFoundHandler
server.go中的NotFoundHandler使用了同樣的手法:
// Error replies to the request with the specified error message and HTTP code.// It does not otherwise end the request; the caller should ensure no further// writes are done to w.// The error message should be plain text.func Error(w ResponseWriter, error string, code int) { w.Header().Set("Content-Type", "text/plain; charset=utf-8") w.Header().Set("X-Content-Type-Options", "nosniff") w.WriteHeader(code) fmt.Fprintln(w, error)}// NotFound replies to the request with an HTTP 404 not found error.func NotFound(w ResponseWriter, r *Request) { Error(w, "404 page not found", StatusNotFound) }// NotFoundHandler returns a simple request handler// that replies to each request with a ``404 page not found'' reply.func NotFoundHandler() Handler { return HandlerFunc(NotFound) }
這裡的NotFound()函數符合HandlerFunc類型的函數原型,所以通過HandlerFunc(NotFound)這個類型轉換,就產生了一個Handler對象。
正如server.go注釋所說的,NotFoundHandler這種都是helper形式的handler。——最開始接觸helper,是接觸ns3源碼的時候,ns3很多代碼就是xxxHelper這種命名方式。