This is a creation in
Article, where the information may have evolved or changed.
Keywords:handlerfunc, Servehttp, Notfoundhandler
Objective
In Go-http, Handlerfunc has been introduced. For the convenience of inspection, come out alone and speak.
Original code
Defined in the Server.go file, as follows.
// 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)}
Function
Handlerfunc is a data type, or strictly speaking, a function type. Anyway, Handlerfunc is a type that is no doubt. Moreover, this handlerfunc implements the Serverhttp method of the handler interface, so Handlerfunc is the specific class of handler.
Customary method
It is customary to define your own first function that conforms to the preceding:
func(ResponseWriter, *Request)
The function is then converted to the Handlerfunc type by "type conversion", which becomes the handler object.
Example
In the Go-http article, the relevant sample code is given, which is copied again (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
The Notfoundhandler in server.go used the same technique:
// 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) }
The NotFound () function here conforms to the function prototype of the Handlerfunc type, so a handler object is generated by the type conversion of Handlerfunc (NotFound).
As the Server.go note says, Notfoundhandler is a helper form of handler. --The first contact with the helper, is the contact NS3 source code, NS3 many codes is xxxhelper this naming method.