Skip to content

HTTP routing in Go services with chi

Use chi to build a Go HTTP server with middleware chains, nested subrouters, URL params, and graceful shutdown. The recommended router pattern for new services.

chi is the router most production Go services we operate use. It is a small library (github.com/go-chi/chi/v5) compatible with net/http, with composable middleware, nested subrouters, and URL-param ergonomics that stdlib still does not match. This article shows the chi layout Stack Harbor uses for new Go HTTP services.

How to verify

A chi-based server boots and responds:

go get github.com/go-chi/chi/v5 github.com/go-chi/chi/v5/middleware
go run .
curl -i http://localhost:8080/healthz
curl -i http://localhost:8080/api/v1/users/42
curl -i -X POST -d '{"email":"a@b"}' http://localhost:8080/api/v1/users

If /healthz returns 200 and the param 42 echoes back in the response, the routing tree is wired.

What’s happening

chi is a trie-based router that implements http.Handler. Routes are registered against the chi.Router, middlewares chain via Use, and subrouters compose via Route (inline) or Mount (external). Every chi handler is just func(w http.ResponseWriter, r *http.Request) — interoperable with the entire stdlib net/http ecosystem.

The two design choices that make chi pleasant in production:

  1. chi.URLParam(r, "name") — string-typed access to path params; no map allocation per request.
  2. Subrouters inherit middleware — r.Route("/api", func(r chi.Router) { r.Use(authMiddleware); r.Get(...) }) applies auth only to /api/*.

chi ships a middleware subpackage with the usuals: Logger, Recoverer, RequestID, Timeout, Compress, StripSlashes, Heartbeat. Production servers tend to compose RequestID -> Logger -> Recoverer -> Compress -> Timeout and then mount their own auth above that.

The procedure

  1. Project layout.

    cmd/api/main.go
    internal/server/server.go
    internal/server/routes.go
    internal/server/middleware.go
    internal/handlers/users.go
  2. Bootstrap the server. internal/server/server.go:

    package server
    
    import (
        "context"
        "errors"
        "log/slog"
        "net/http"
        "time"
    
        "github.com/go-chi/chi/v5"
        "github.com/go-chi/chi/v5/middleware"
    )
    
    type Server struct {
        http *http.Server
        log  *slog.Logger
    }
    
    func New(addr string, log *slog.Logger) *Server {
        r := chi.NewRouter()
        r.Use(middleware.RequestID)
        r.Use(middleware.RealIP)
        r.Use(loggerMW(log))
        r.Use(middleware.Recoverer)
        r.Use(middleware.Timeout(15 * time.Second))
        r.Use(middleware.Compress(5))
    
        r.Get("/healthz", func(w http.ResponseWriter, r *http.Request) {
            w.WriteHeader(http.StatusOK)
        })
    
        registerRoutes(r)
    
        return &Server{
            http: &http.Server{
                Addr:              addr,
                Handler:           r,
                ReadHeaderTimeout: 5 * time.Second,
                ReadTimeout:       30 * time.Second,
                WriteTimeout:      30 * time.Second,
                IdleTimeout:       60 * time.Second,
            },
            log: log,
        }
    }
    
    func (s *Server) Run(ctx context.Context) error {
        errCh := make(chan error, 1)
        go func() {
            if err := s.http.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
                errCh <- err
            }
        }()
        select {
        case <-ctx.Done():
            shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
            defer cancel()
            return s.http.Shutdown(shutdownCtx)
        case err := <-errCh:
            return err
        }
    }
  3. Register routes. internal/server/routes.go:

    func registerRoutes(r chi.Router) {
        r.Route("/api/v1", func(r chi.Router) {
            r.Use(requireJWT)
            r.Route("/users", func(r chi.Router) {
                r.Get("/{id}", handlers.GetUser)
                r.Post("/", handlers.CreateUser)
                r.Put("/{id}", handlers.UpdateUser)
                r.Delete("/{id}", handlers.DeleteUser)
            })
            r.Route("/orders", func(r chi.Router) {
                r.Get("/{id}", handlers.GetOrder)
                r.Post("/", handlers.CreateOrder)
            })
        })
        r.Group(func(r chi.Router) {
            r.Use(rateLimit(50))
            r.Post("/webhooks/stripe", handlers.StripeWebhook)
        })
    }

    Route creates a nested subrouter that inherits middleware. Group creates an anonymous subrouter (no prefix) — useful for “just add this middleware to a few routes”.

  4. Read params, write JSON. A handler:

    func GetUser(w http.ResponseWriter, r *http.Request) {
        id := chi.URLParam(r, "id")
        u, err := store.FindUser(r.Context(), id)
        if err != nil {
            http.Error(w, "not found", http.StatusNotFound)
            return
        }
        w.Header().Set("Content-Type", "application/json")
        _ = json.NewEncoder(w).Encode(u)
    }
  5. Custom middleware. Any func(next http.Handler) http.Handler:

    func requireJWT(next http.Handler) http.Handler {
        return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
            token := r.Header.Get("Authorization")
            claims, err := verifyJWT(token)
            if err != nil {
                http.Error(w, "unauthorized", http.StatusUnauthorized)
                return
            }
            ctx := context.WithValue(r.Context(), userKey{}, claims)
            next.ServeHTTP(w, r.WithContext(ctx))
        })
    }
  6. Health and readiness. Split liveness from readiness:

    r.Get("/healthz", livenessHandler)        // process alive
    r.Get("/readyz", readinessHandler(db))    // dependencies reachable

    Liveness should never query downstream (a slow DB should not kill the pod). Readiness can.

  7. Test handlers with httptest.

    func TestGetUser(t *testing.T) {
        r := chi.NewRouter()
        r.Get("/users/{id}", GetUser)
    
        req := httptest.NewRequest(http.MethodGet, "/users/42", nil)
        w := httptest.NewRecorder()
        r.ServeHTTP(w, req)
        if w.Code != 200 { t.Fatalf("got %d", w.Code) }
    }

Common pitfalls

  • middleware.Timeout cancels the request context but does not close the underlying connection. Long-running handlers must still check r.Context().Err() after expensive operations.
  • Recoverer recovers panics into a 500. Fine for graceful degradation, but you lose the stack trace in client-facing logs. Add structured logging in the recovery path.
  • Use after a route declaration is silently ignored. Always declare middleware before routes on the same router.
  • chi.Router is not *chi.Mux. When wiring tests, accept the interface so a *chi.Mux and a chi.Router returned from Route are interchangeable.
  • Default http.Server timeouts are zero (unlimited). Always set ReadHeaderTimeout, ReadTimeout, WriteTimeout, and IdleTimeout — a slowloris client otherwise lives indefinitely.

Stack Harbor scaffolds new Go HTTP services on chi by default, with the middleware order tested in CI and graceful shutdown wired to a signal-handler context. See how that fits into our managed operations practice for Go fleets.