Handlers
An http.Handler has one method: ServeHTTP(http.ResponseWriter, *http.Request). http.HandlerFunc adapts a function to that interface. Everything that serves HTTP in Go is a handler.
Detailed Explanation
The server accepts a connection, parses a request, and calls handler.ServeHTTP. Your job is to write a status and a body, or pass the request to another handler. There is no controller base class. A struct with ServeHTTP, or a function converted with HandlerFunc, is enough.
ResponseWriter. WriteHeader(code) sets the status; the first Write implies 200 if you did not. You cannot change the status after the header is sent. Write writes the body. Header map Header() must be set before WriteHeader.
The request is a value you must not keep. Do not store *Request on a background struct after ServeHTTP returns; the server reuses it. Copy fields you need. Use r.Context() for cancel, not a goroutine that outlives the request without a detached context.
Errors. There is no error return on ServeHTTP. You write a 4xx/5xx and log. A helper func writeErr(w, code, err) keeps that consistent. Panics are recovered by Server by default; still prefer returning via status codes.
What it costs. A handler should do little: parse, call a service, encode JSON. Heavy work belongs in functions you can test without HTTP. httptest then checks the wiring.
Code Examples
package main
import (
"encoding/json"
"net/http"
)
type userHandler struct{ greet string }
func (h userHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{"msg": h.greet})
}
func health(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNoContent)
}
func main() {
mux := http.NewServeMux()
mux.Handle("/user", userHandler{greet: "hi"})
mux.Handle("GET /health", http.HandlerFunc(health))
http.ListenAndServe(":8080", mux)
}Common Gotchas
Writing the body then `WriteHeader` does not change the status
the header was already sent as 200.
`HandlerFunc(f)` is an adapter
`f` must match `func(ResponseWriter, *Request)`.