HTTP servers
Use the standard `net/http` server lifecycle deliberately: timeouts, shutdown, and handler ownership matter more than routing sugar.
Canonical guidance
- own the
http.Serverlifecycle explicitly - configure timeouts intentionally
- make shutdown and request cancellation part of the design
Use when
- API servers
- internal admin servers
- background services exposing health or metrics endpoints
Avoid
http.ListenAndServewith no shutdown path in long-lived services- handlers that keep request-owned work running after cancellation
- assuming a router framework replaces server lifecycle design
Preferred pattern
srv := &http.Server{
Addr: ":8080",
Handler: mux,
ReadTimeout: 5 * time.Second,
WriteTimeout: 10 * time.Second,
}
Anti-pattern
- starting a production server with defaults and no graceful shutdown because “the orchestrator will kill it anyway”
Explanation: This anti-pattern is tempting because it reduces boilerplate, but it turns restarts and overload into correctness problems.
Why
- most HTTP server bugs in Go are lifecycle and timeout bugs, not routing bugs
Related pages
Sources
- net/http package - Go Team
- Go Concurrency Patterns: Context - Sameer Ajmani