Handler in Go’s net/http package
tags: learning go programming
content
in Go’s net/http package, a handler is:
type Handler interface {
ServeHTTP(http.ResponseWriter, *http.Request)
}- as long as a type implements
ServeHTTP, it’s qualified as aHandler - when a request comes in, the http server finds the corresponding handler and calls its
ServeHTTPmethod
HandlerFunc:
-
type HandlerFunc func(http.ResponseWriter, *http.Request) -
it’s a type
-
any function that has the same signature can be converted to
HandlerFunc -
it has
ServeHTTPmethod, so it implements theHandlerinterface implicitly
type HandlerFunc func(http.ResponseWrite, *http.Request)
func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) {
f(w, r) // it just calls HandlerFunc itself
}