net/http
Prefer the standard library HTTP stack unless you have a concrete need not met by it.
Canonical guidance
- start with
net/http - handlers should be small and explicit about request-scoped work
- propagate request context through downstream calls
- configure server and client timeouts deliberately
Use when
- building APIs
- middleware design
- HTTP clients and servers
Avoid
- global shared request state
- ignoring request context
- default timeouts everywhere in production network code
Preferred pattern
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if err := s.handle(r.Context(), w, r); err != nil {
http.Error(w, "internal error", http.StatusInternalServerError)
}
}
Anti-pattern
- handlers that spawn detached goroutines with request-owned resources
Explanation: This anti-pattern is tempting when handlers need to keep work running, but detached goroutines often retain request-owned resources after the caller is gone.
Why
- the standard library already encodes the dominant Go HTTP model
- many correctness bugs here are lifecycle and timeout bugs, not routing bugs
Related pages
Sources
- net/http package - Go Team
- Go Concurrency Patterns: Context - Sameer Ajmani