HTTP Servers and Clients in Go
Build HTTP servers with net/http routing and timeouts, and call APIs with clients that time out, close bodies and check status codes.
net/http covers both sides of HTTP. This section shows a production-ready server and a client that will not hang or leak connections.
Writing an HTTP Server
mux := http.NewServeMux()
mux.HandleFunc("GET /users/{id}", getUser)
Method and path patterns, JSON responses, server timeouts and graceful shutdown.
Making HTTP Requests
Clients with timeouts, defer resp.Body.Close(), status checks, JSON POST requests and context cancellation.
No timeouts by default:
Both http.ListenAndServe and http.Get use defaults with no timeouts. Set them yourself on both sides.
Summary
Use your own ServeMux and http.Server with timeouts, and a shared http.Client with a timeout for outgoing calls.
Writing an HTTP Server in Go
Build an HTTP server with net/http, use the Go 1.22 router with methods and path values, return JSON, set server timeouts, and shut down cleanly.
Making HTTP Requests in Go
Call APIs with net/http, set client timeouts, always close response bodies, check status codes, send JSON, and cancel requests with context.