This has confused me for the last month of learning Go:
func Auth(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { // hmmmm
// ...
next.ServeHTTP(w, r)
}
}
here we can see that the Auth func returns type http.HandlerFunc
. That type is just a func. So when you call next.ServeHTTP
, when/where is that method defined?
https://golang.org/src/net/http/server.go?s=59707:59754#L1950
// 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)
}
Literally any function with the signature func(ResponseWriter, *Request)
can be cast to a HandlerFunc
, which gives it the method ServeHTTP
- which then simply calls the function.