While chaining handlers, the function has a return type of Handler, but it actually returns a HandlerFunc. This does not throw any error.
How is HandlerFunc accepted in place of a Handler, the prior being a function type and the latter being a interface type?
func log(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
...
})
}
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.
The http.Handler
is an interface:
type Handler interface {
ServeHTTP(ResponseWriter, *Request)
}
The http.HandlerFunc
is a type:
type HandlerFunc func(ResponseWriter, *Request)
// ServeHTTP calls f(w, r).
func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) {
f(w, r)
}
http.Handler
is an interface. http.HandlerFunc
is a concrete type that implements that interface. This is all documented in the http
package documentation. If interfaces are new to you, start with A Tour of Go.