By Abhijith N M · Reviewed 24 October 2026 · Editorial standards
The net/http package gives you a production server in one type. http.Server owns the listener, the timeouts, the connection pool and the lifecycle. http.ServeMux routes by method and path using patterns such as GET /v1/stats (Go 1.22+) and rejects the wrong method with 405 automatically. You provide handlers; the server provides the protocol.
Configure every timeout. ReadHeaderTimeout defends against slowloris-style attacks, ReadTimeout bounds the whole request body, WriteTimeout bounds the response write and IdleTimeout closes keep-alive connections that are no longer active. Leaving these at zero means no timeout, which is a production incident waiting for a slow client.
A middleware is a function from http.Handler to http.Handler. It runs code before and after the inner handler, which is exactly what request IDs, logging, recovery, authentication and rate limiting need. Compose them outside-in: the outermost middleware runs first on the way in and last on the way out. Keep each middleware single-purpose so the chain reads like a list of guarantees.
Server.Shutdown first stops accepting new connections, then waits for active handlers to finish, up to the context's deadline. If the deadline expires it returns an error and you decide whether to force-close. ListenAndServe returns http.ErrServerClosed on a clean shutdown, so treat that sentinel as success. signal.NotifyContext turns SIGINT/SIGTERM into a context that triggers the whole sequence.
package main
import (
"context"
"errors"
"fmt"
"log/slog"
"net/http"
"os"
"os/signal"
"syscall"
"time"
)
func withRequestID(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-Request-ID", "req-demo")
next.ServeHTTP(w, r)
})
}
func newRouter() http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte("ok"))
})
return withRequestID(mux)
}
func run(ctx context.Context, addr string) error {
srv := &http.Server{
Addr: addr,
Handler: newRouter(),
ReadHeaderTimeout: 5 * time.Second,
ReadTimeout: 10 * time.Second,
WriteTimeout: 15 * time.Second,
IdleTimeout: 60 * time.Second,
}
shutdownDone := make(chan struct{})
go func() {
defer close(shutdownDone)
<-ctx.Done()
shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := srv.Shutdown(shutdownCtx); err != nil {
slog.Error("shutdown did not finish", "error", err)
}
}()
slog.Info("listening", "addr", addr)
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
return fmt.Errorf("serve: %w", err)
}
<-shutdownDone
return nil
}
func main() {
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
if err := run(ctx, ":8080"); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}| Piece | Do this | Why |
|---|---|---|
ReadHeaderTimeout | 5-10 seconds | Bounds slow-header attacks |
ReadTimeout / WriteTimeout | Set both | Bounds body and response time |
IdleTimeout | 30-60 seconds | Recycles unused keep-alive connections |
http.ErrServerClosed | Treat as success | It is the normal return of Shutdown |
| Middleware order | Outer first | Request IDs must exist before logging |
| Shutdown timeout | Shorter than the orchestrator's grace period | The next signal can still kill the process |
Key takeaways
http.Server plus ServeMux gives routing, timeouts and lifecycle without a framework.
Set ReadHeaderTimeout, ReadTimeout, WriteTimeout and IdleTimeout explicitly.
Middleware is a handler that wraps a handler; compose it outside-in and keep each piece single-purpose.
Server.Shutdown stops accepting, then drains in-flight requests up to a deadline.
Treat http.ErrServerClosed as a clean exit and let main choose the process exit code.
Written and edited by the nexGenCoders team. Spotted a mistake? Tell us and we will fix it.
Don't lose this lesson
Create a free account to save your progress, keep your streak, and work toward a shareable certificate.