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 a Handler
  • when a request comes in, the http server finds the corresponding handler and calls its ServeHTTP method

HandlerFunc:

  • net/http - 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 ServeHTTP method, so it implements the Handler interface implicitly

type HandlerFunc func(http.ResponseWrite, *http.Request)
func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) {
	f(w, r)  // it just calls HandlerFunc itself
}

up

down

reference