Go Reference ยท Networking and the Web
Go http.Handler interface
Reference for Go's http.Handler interface and http.HandlerFunc adapter: the ServeHTTP method, writing middleware, wrapping handlers and built-in handlers.
http.Handler is the interface at the heart of Go's web server. It has one method: ServeHTTP(http.ResponseWriter, *http.Request). Anything that implements it can answer HTTP requests: a struct holding a database handle, a router, a file server, or a wrapper that adds logging.
http.HandlerFunc is a function type with a ServeHTTP method that calls the function itself. It lets an ordinary function with the right signature act as a Handler through a simple conversion.
type Handler interface { ServeHTTP(ResponseWriter, *Request) }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Syntax
type Handler interface { ServeHTTP(ResponseWriter, *Request) } type HandlerFunc func(ResponseWriter, *Request) func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) func NotFoundHandler() Handler func RedirectHandler(url string, code int) Handler func FileServer(root FileSystem) Handler func FileServerFS(fsys fs.FS) Handler func StripPrefix(prefix string, h Handler) Handler func TimeoutHandler(h Handler, dt time.Duration, msg string) Handler func MaxBytesHandler(h Handler, n int64) Handler
| Name | Description |
|---|---|
w |
Where the handler writes the status line, headers and body. |
r |
The incoming request. Do not modify it; clone it with r.WithContext or r.Clone if you need changes. |
Rules for ServeHTTP:
- The request is finished when
ServeHTTPreturns. Do not keep usingworr.Bodyafterwards, including from goroutines you started. - Do not read from
r.Bodyafter you have started writing the response (HTTP/1.x may not support it). - A panic in a handler is recovered by the server (the connection is closed and the panic is logged), except for
http.ErrAbortHandler, which aborts silently. - Handlers are called from many goroutines at once. A handler value with mutable fields needs a mutex.
FileServerFSneeds Go 1.22.
Usage notes
- Middleware pattern: a function
func(http.Handler) http.Handler. Order matters:logging(auth(app))logs first, then checks authentication. - Pass information down with the context. Use
r.WithContext(context.WithValue(...))with a private key type, not global variables. - Wrap the
ResponseWriterto observe the response, for example to capture the status code for logs. Embed the original writer and overrideWriteHeader. ImplementUnwrap() http.ResponseWritersohttp.ResponseControllerstill reaches optional features such as flushing. - Handler or HandlerFunc? Use a struct when the handler has state or dependencies, and a function for stateless ones.
- Test without a network using
httptest.NewRecorderas shown above; see net/http/httptest. ServeMuxis aHandlertoo, which is why routers nest and wrap in the same way.