Stage 3 · Build
HTTP & REST APIs
net/http Handlers
Build handlers with http.HandlerFunc, ResponseWriter, Request, ServeMux, and server timeouts.
The Handler Interface
Go's net/http package defines a single interface for handling requests: Handler. It has one method, ServeHTTP(ResponseWriter, Request). Every HTTP handler in Go implements this interface, either directly or through the convenience type http.HandlerFunc.
In Go, every endpoint is a handler. Middleware wraps handlers. Routers map paths to handlers. Everything revolves around this single abstraction.
ResponseWriter
ResponseWriter is how you write the HTTP response. You set the status code, add headers, and write the body. The order matters: call WriteHeader before Write, or Write will implicitly send 200 OK.
Request Object
The Request object gives you access to everything about the incoming request: method, URL, headers, body, query parameters, path parameters (from routers), and the context for cancellation and deadlines.
ServeMux Routing
Go 1.22 enhanced ServeMux with method matching and path parameters. For most applications, the standard library router is sufficient. For more complex routing, use chi or Gin.
Server Timeouts
Without timeouts, slow clients can hold connections open forever, exhausting your server's resources. Configure ReadTimeout, WriteTimeout, and IdleTimeout to prevent this.
Without WriteTimeout, a handler that blocks forever will leak a goroutine and hold a connection indefinitely. This is one of the most common causes of resource exhaustion in Go HTTP servers.
Full Server Example
Mark this lesson complete to store local progress and unlock a cleaner resume path the next time you visit.