The chi router and context.Context

Route requests with chi, add the standard middleware (request id, logger, recoverer), read the request context, and understand why context carries cancellation and deadlines.

Learning outcomes

  • Create a chi router, register routes by method and path, and group middleware with Use.
  • Use chi middleware for request id, logging and panic recovery.
  • Explain what context.Context carries and why handlers pass r.Context() down.
  • Create a context with a timeout and cancel it with defer.
  • Start and gracefully stop an http.Server.
Prerequisite conceptsHTTP handlerHTTP middleware

From handlers to a router

In the previous lesson, you used Go's net/http package to build handlers, register routes with http.ServeMux, and wrap handlers with middleware.

As your API grows, manually registering every route and combining middleware becomes harder to manage. You also need a convenient way to define route groups and extract parameters from URL paths.

The chi router is a small HTTP router built on top of Go's standard net/http handler model. It gives you convenient routing features without replacing the interfaces you already learned.

This distinction matters: everything from lesson 1.16 still applies. Your handlers still receive http.ResponseWriter and *http.Request. Middleware still wraps http.Handler. Your tests can still use net/http/httptest.

In this lesson, you will use chi to organise the API, learn how request contexts carry cancellation and deadlines, and assemble the pieces of the Week 1 API server.

Installing chi

The project uses chi version 5.

From the backend directory, add the dependency:

bash
go get github.com/go-chi/chi/v5

Chi also provides commonly used middleware in a separate package within the same module:

go
go get github.com/go-chi/chi/v5/middleware

You do not need a separate module for the middleware package. It is included in the chi module.

Your imports will usually look like this:

go
import (
	"net/http"

	"github.com/go-chi/chi/v5"
	"github.com/go-chi/chi/v5/middleware"
)

Creating a chi router

Create a router with chi.NewRouter():

go
package main

import (
	"fmt"
	"net/http"

	"github.com/go-chi/chi/v5"
)

func main() {
	r := chi.NewRouter()

	r.Get("/healthz", func(w http.ResponseWriter, req *http.Request) {
		fmt.Fprintln(w, "ok")
	})

	http.ListenAndServe(":8080", r)
}

The router implements http.Handler, so it can be passed directly to http.ListenAndServe or assigned to the Handler field of an http.Server.

Registering routes by method

HTTP routes usually combine a method and a path. Chi provides methods such as:

  • r.Get(path, handler) for GET requests.
  • r.Post(path, handler) for POST requests.
  • r.Put(path, handler) for PUT requests.
  • r.Patch(path, handler) for PATCH requests.
  • r.Delete(path, handler) for DELETE requests.

For example:

go
r.Get("/restaurants", listRestaurantsHandler)
r.Post("/restaurants", createRestaurantHandler)
r.Get("/restaurants/{restaurantID}", getRestaurantHandler)

The same path can have different handlers for different HTTP methods.

A request to GET /restaurants matches the first route. A request to POST /restaurants matches the second.

If a request uses a method that is not registered for a matching path, chi can return a method-related response rather than invoking one of the other handlers.

Route parameters

A route parameter is a variable part of a URL path.

Consider:

GET /restaurants/42

You can define the route with a named parameter:

go
r.Get("/restaurants/{restaurantID}", getRestaurantHandler)

Read the value inside the handler with chi.URLParam:

go
func getRestaurantHandler(w http.ResponseWriter, r *http.Request) {
	restaurantID := chi.URLParam(r, "restaurantID")

	fmt.Fprintf(w, "restaurant id: %s\n", restaurantID)
}

The parameter is returned as a string. If your application expects a numeric identifier, parse it and handle invalid input.

Do not assume that a route parameter is valid simply because the router matched the path.

Route groups

A route group lets you organise related routes under a common path prefix.

go
r.Route("/restaurants", func(r chi.Router) {
	r.Get("/", listRestaurantsHandler)
	r.Post("/", createRestaurantHandler)
	r.Get("/{restaurantID}", getRestaurantHandler)
})

The routes inside the group are registered relative to /restaurants.

This is useful when a backend has multiple resources, such as restaurants, menus, orders, and users.

Groups and shared middleware

A group lets you apply middleware to a set of routes without applying it to the entire router.

go
r.Group(func(r chi.Router) {
	r.Use(authenticationMiddleware)

	r.Get("/orders", listOrdersHandler)
	r.Get("/orders/{orderID}", getOrderHandler)
})

Both order routes use the authentication middleware. Routes registered outside this group do not inherit it.

A group does not automatically create a path prefix. Use r.Route when you want a path prefix, and r.Group when you want a separate middleware or routing configuration scope.

Trailing slashes

These paths are different strings:

/restaurants
/restaurants/

Do not assume that every router treats them as identical. Chi supports middleware for redirecting trailing slashes, but the route patterns you register should still be deliberate.

For example, registering:

go
r.Get("/restaurants", listRestaurantsHandler)

does not mean you should casually assume that /restaurants/ will behave identically in every configuration.

Choose a consistent route style and test the paths your clients actually use.

Inspecting registered routes

Chi provides chi.Walk, which lets you iterate over registered routes and inspect their methods and patterns.

This can be useful for diagnostics, documentation generation, or checking which routes are registered when the server starts.

You do not need it for the Week 1 exercise, but it is useful to know that the router can expose its route structure programmatically.

Middleware in chi

You already learned that middleware has the shape:

go
func(http.Handler) http.Handler

Chi uses the same model. Register middleware with r.Use:

go
r := chi.NewRouter()

r.Use(requestLoggingMiddleware)
r.Use(authenticationMiddleware)

r.Get("/healthz", healthHandler)

Middleware is applied in registration order. The first registered middleware is the outermost layer. A request passes through it before reaching the next layer.

When the handler finishes, control returns through the middleware stack in reverse order.

Standard chi middleware

Chi includes middleware for common HTTP server concerns. Three useful examples are:

  • middleware.RequestID adds a request identifier to the request context and response headers.
  • middleware.Logger logs HTTP request information.
  • middleware.Recoverer recovers from panics in downstream handlers and prevents an individual request panic from crashing the whole server process.

Register them near the beginning of router setup:

go
r := chi.NewRouter()

r.Use(middleware.RequestID)
r.Use(middleware.Logger)
r.Use(middleware.Recoverer)

The request ID is useful when connecting logs from different parts of a request. The logger records request information, while the recovery middleware provides a safety boundary around handlers.

Middleware order matters

Suppose you register the rate limiter before the logger:

go
r.Use(rateLimitMiddleware)
r.Use(middleware.Logger)

If the rate limiter rejects a request and returns without calling the next handler, the logger never sees that request.

For this course, put the logger before the limiter:

go
r.Use(middleware.RequestID)
r.Use(middleware.Logger)
r.Use(middleware.Recoverer)
r.Use(rateLimitMiddleware)

Now rejected requests pass through the logger before the limiter rejects them.

The outer middleware can also observe the response after the inner middleware finishes. This is why the order affects both request processing and response handling.

Middleware stack

Show a chi router with RequestID, Logger, Recoverer, and RateLimit middleware above the GET /healthz handler; show the request passing through each layer and the response travelling back, with RateLimit able to reject before the handler runs.Show a chi router with RequestID, Logger, Recoverer, and RateLimit middleware above the GET /healthz handler; show the request passing through each layer and the response travelling back, with RateLimit able to reject before the handler runs.

Understanding context.Context

The context.Context type carries information about the lifetime of an operation.

A context can communicate:

  • Cancellation: the operation should stop because its caller no longer needs it.
  • A deadline: the operation should finish before a specified time.
  • Request-scoped values: values associated with an operation that must travel across API boundaries.

A context is not a general-purpose storage object. It exists to coordinate the lifetime of work and carry a small amount of request-scoped metadata.

Every incoming http.Request already has a context. Access it with:

go
ctx := r.Context()

You do not need to create a new context just to handle an incoming request.

Why request contexts matter

Imagine a mobile app sends a request to list restaurants. Your handler starts a database query. Before the query finishes, the user closes the app or the connection is cancelled.

The server may detect that the client has disconnected. The request context is then cancelled, allowing operations that use that context to stop unnecessary work.

The request context is also cancelled when the handler returns.

This is important because a request can trigger multiple operations. If the original request is no longer active, those operations should not continue consuming resources without a reason.

Passing context to functions

Functions that perform I/O should generally accept a context as their first parameter, conventionally named ctx.

I/O means input or output involving an external resource, such as a database, network connection, file, or remote service.

For example:

go
func loadRestaurant(ctx context.Context, restaurantID string) error {
	return nil
}

The example does not perform I/O yet, but it shows the expected function signature.

When the handler calls this function, pass the request context:

go
func getRestaurantHandler(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()

	if err := loadRestaurant(ctx, "42"); err != nil {
		http.Error(w, "could not load restaurant", http.StatusInternalServerError)
		return
	}

	w.WriteHeader(http.StatusOK)
}

This keeps the operation connected to the lifetime of the incoming request.

Do not casually replace the request context with context.Background(). Doing so disconnects the operation from request cancellation. A database query might continue even after the client has disconnected.

Creating and cancelling contexts

The context package provides functions for creating contexts.

context.Background

context.Background() returns an empty context. It has no deadline, no cancellation signal, and no values.

It is commonly used as the root context for an application or in a test where no parent context exists.

go
ctx := context.Background()

Do not use it inside an HTTP handler as a replacement for r.Context() when starting request-related work.

context.WithCancel

context.WithCancel creates a child context that can be cancelled explicitly.

go
package main

import (
	"context"
	"fmt"
)

func main() {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	cancel()

	fmt.Println(ctx.Err())
}

The returned cancel function signals that the operation should stop. Calling it more than once is safe.

Always call the cancellation function when you are finished with the context. The usual pattern is:

go
ctx, cancel := context.WithCancel(parent)
defer cancel()

This releases resources associated with the derived context and ensures that child operations are not left running unnecessarily.

Checking for cancellation

The context exposes Err() to check whether it has been cancelled or its deadline has expired.

The two common errors are:

  • context.Canceled: the context was explicitly cancelled or its parent was cancelled.
  • context.DeadlineExceeded: the context's deadline passed before the operation completed.

For example:

go
if err := ctx.Err(); err != nil {
	return err
}

This is useful when a function can stop work at a natural checkpoint.

For operations that wait, you can select on ctx.Done():

go
func waitForWork(ctx context.Context) error {
	select {
	case <-ctx.Done():
		return ctx.Err()
	}
}

Done() returns a channel that is closed when the context is cancelled or its deadline expires. A select lets a goroutine wait for cancellation alongside other events.

Checking ctx.Err() does not forcibly stop a function. The function must cooperate by checking the context or passing it to an operation that supports cancellation.

Bounded operations with context timeouts

A backend should not wait forever for an external dependency.

A database query or Redis command can become slow because of network problems, server load, connection issues, or a dependency failure. If every incoming request waits indefinitely, slow operations can accumulate and consume resources.

A context timeout gives an operation a maximum amount of time to run.

Use context.WithTimeout to derive a child context with a deadline:

go
ctx, cancel := context.WithTimeout(parent, 200*time.Millisecond)
defer cancel()

The child context inherits cancellation from its parent and adds its own deadline.

If the parent is cancelled first, the child is cancelled too. If the child's deadline expires first, the child is cancelled even if the parent remains active.

Choosing a timeout

A short timeout is appropriate for a dependency operation that should complete quickly.

For example, a backend might use a timeout between 50 milliseconds and 500 milliseconds for a Redis operation, depending on the expected latency and the request's overall time budget.

The correct value is not universal. It depends on the dependency, network conditions, service objectives, and how much time remains in the overall request deadline.

The key is to make the operation bounded and to derive its context from the incoming request:

go
func checkSomething(ctx context.Context) error {
	opCtx, cancel := context.WithTimeout(ctx, 200*time.Millisecond)
	defer cancel()

	return performOperation(opCtx)
}

Here, performOperation represents an I/O function that accepts a context. The child timeout cannot extend the parent's deadline. If the request has only 50 milliseconds remaining, the operation gets at most that much time.

When the deadline expires, a context-aware operation should stop and return an error. That error may be context.DeadlineExceeded, or it may be a dependency-specific error that wraps or accompanies the cancellation.

Do not ignore context errors and continue retrying indefinitely. A retry should respect the remaining request deadline.

Context parent and child

Show a request parent context creating a child WithTimeout of 50 ms; show the child deadline expiring first, a Redis call returning context deadline exceeded, and cancellation of the parent also cancelling the child.Show a request parent context creating a child WithTimeout of 50 ms; show the child deadline expiring first, a Redis call returning context deadline exceeded, and cancellation of the parent also cancelling the child.

Contexts and the rate limiter

In Week 1, your Limiter interface is:

go
type Limiter interface {
	Allow(key string) bool
}

It does not accept a context because the in-memory limiter performs a small local operation.

In later weeks, some limiter operations will involve Redis. Those operations perform network I/O and need a context so they can stop when the request is cancelled or the dependency timeout expires.

You will learn to pass a context into those operations when you reach the Redis implementation. Do not add a context parameter to the current Week 1 interface just because you have learned about contexts.

Context values are another capability of the context package. They can carry request-scoped metadata across API boundaries, but they should not be used as a general-purpose parameter bag. Week 3 will cover their use in authentication and request identity.

Putting together the API server

The Week 1 API server lives at:

backend/cmd/api/main.go

It will use chi, the standard middleware, the rate-limit middleware from the previous lesson, and an http.Server with explicit timeouts.

The final exercise asks you to assemble the server. The following pieces show the structure without giving you the complete main.go implementation.

Piece 1: Imports and logger

Start with the packages required for the server:

go
package main

import (
	"encoding/json"
	"errors"
	"log"
	"net/http"
	"os"
	"time"

	"github.com/go-chi/chi/v5"
	"github.com/go-chi/chi/v5/middleware"
)

The standard logger is sufficient for this small server:

go
logger := log.New(os.Stdout, "api ", log.LstdFlags)

You can use this logger for startup and server errors. Chi's middleware.Logger separately logs HTTP requests.

Piece 2: The health handler

The /healthz endpoint returns a small JSON response:

go
func healthHandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)

	if err := json.NewEncoder(w).Encode(map[string]bool{
		"ok": true,
	}); err != nil {
		return
	}
}

A health endpoint is commonly polled by load balancers and orchestration systems to determine whether an application is healthy.

For this exercise, /healthz is rate limited only so you can easily observe the 429 response. This is a demonstration choice, not a production recommendation.

A real health check must never be rate limited. Load balancers and orchestrators need to poll it reliably, especially when the application is under heavy load. If the health check is rejected because of a rate limit, infrastructure may incorrectly conclude that a healthy service is unavailable.

Piece 3: Router and middleware

Create the router and register the standard middleware:

go
func newRouter(rateLimitMiddleware func(http.Handler) http.Handler) http.Handler {
	r := chi.NewRouter()

	r.Use(middleware.RequestID)
	r.Use(middleware.Logger)
	r.Use(middleware.Recoverer)
	r.Use(rateLimitMiddleware)

	r.Get("/healthz", healthHandler)

	return r
}

This function receives the rate-limit middleware as a dependency. It does not decide how the limiter is constructed.

The ordering is deliberate:

  1. RequestID establishes a request identifier.
  2. Logger records the request.
  3. Recoverer protects the downstream handler chain from panics.
  4. Rate limiting decides whether the request can continue.
  5. The health handler writes the response.

The exercise will ask you to supply the rate-limit middleware. Keep the router independent of the limiter's construction so that the routing setup remains easy to test.

Piece 4: HTTP server configuration

Use an http.Server rather than relying on the defaults of http.ListenAndServe:

go
server := &http.Server{
	Addr:              ":8080",
	Handler:           router,
	ReadHeaderTimeout: 5 * time.Second,
	ReadTimeout:       15 * time.Second,
	WriteTimeout:      30 * time.Second,
	IdleTimeout:       60 * time.Second,
}

These are the same timeout categories introduced in lesson 1.16:

  • ReadHeaderTimeout bounds the time spent reading request headers.
  • ReadTimeout bounds the time spent reading the request.
  • WriteTimeout bounds the time spent writing the response.
  • IdleTimeout bounds how long an idle keep-alive connection can remain open.

The values are suitable as teaching defaults, not a universal production configuration.

Piece 5: Starting the server and handling errors

Start the server with ListenAndServe:

go
err := server.ListenAndServe()
if err != nil && !errors.Is(err, http.ErrServerClosed) {
	logger.Fatal(err)
}

http.ErrServerClosed is returned when the server has been shut down normally. It should not be treated as an unexpected startup or runtime failure.

Graceful shutdown means stopping the server from accepting new requests while allowing active requests to finish within a bounded period. It is important for deployments and rolling restarts. Later weeks will build this behaviour into the project. You do not need to implement signal handling or graceful shutdown in this exercise.

Piece 6: The rate limiter wiring is yours

The router expects a middleware function:

go
func(http.Handler) http.Handler

In the exercise, construct the in-memory token bucket with:

  • Capacity: 5 tokens.
  • Refill rate: 1 token per second.

Then adapt it into the rate-limit middleware expected by newRouter.

Keep this wiring separate from route registration. The router should receive a ready-to-use middleware dependency rather than knowing how the limiter is configured.

Do not put the limiter after the handler or create a new limiter for every request. The same limiter instance must be shared by requests so that they consume from the same bucket.

Running and observing the server

Once you have completed the exercise, start the API server from the backend directory:

bash
go run ./cmd/api

In another terminal, send repeated requests:

bash
for i in $(seq 1 8); do
  curl -s -o /dev/null -w "%{http_code}\n" http://localhost:8080/healthz
done

The command prints only the HTTP status code for each request.

With a capacity of five and no time between requests, you should see successful responses until the bucket is exhausted, followed by 429 responses.

Wait before trying again:

bash
sleep 2
curl -i http://localhost:8080/healthz

The -i option includes response headers, allowing you to inspect Retry-After when a request is rejected.

The exact sequence depends on the time between requests and the token bucket's refill behaviour. Do not assume every request in a loop arrives at precisely the same instant.

Testing chi handlers and request contexts

You can test chi routes without opening a port, just as you tested standard handlers in lesson 1.16.

Use httptest.NewRecorder to capture the response and httptest.NewRequest to construct a request:

go
func TestHealthz(t *testing.T) {
	r := chi.NewRouter()
	r.Get("/healthz", healthHandler)

	req := httptest.NewRequest(http.MethodGet, "/healthz", nil)
	rec := httptest.NewRecorder()

	r.ServeHTTP(rec, req)

	if rec.Code != http.StatusOK {
		t.Fatalf("status = %d, want %d", rec.Code, http.StatusOK)
	}
}

For tests that need a specific context, use http.NewRequestWithContext:

go
ctx, cancel := context.WithCancel(context.Background())
defer cancel()

req, err := http.NewRequestWithContext(
	ctx,
	http.MethodGet,
	"/healthz",
	nil,
)
if err != nil {
	t.Fatal(err)
}

This lets you test how a handler behaves when the request context is cancelled or has a deadline.

A context-aware handler or dependency should observe cancellation and stop work when appropriate. A test can cancel the context and verify the resulting behaviour without relying on real network connections.

Common mistakes to avoid

Treating chi as a different handler system

Chi is built on net/http. Continue using http.Handler, http.HandlerFunc, http.ResponseWriter, and *http.Request.

Registering middleware in the wrong order

The first middleware is the outermost layer. If the limiter runs before the logger, rejected requests may never be logged.

Confusing route groups with path prefixes

Use r.Route to create a path prefix. Use r.Group to create a shared middleware or configuration scope without introducing a new path prefix.

Replacing the request context with Background

An operation started by an HTTP request should normally derive its context from r.Context(). Replacing it with context.Background() discards the request's cancellation and deadline.

Forgetting to call cancel

Always defer the cancellation function returned by WithCancel or WithTimeout. This releases resources associated with the derived context.

Giving every operation an unlimited lifetime

External calls should have sensible time bounds. Derive a short timeout from the request context instead of allowing a dependency call to wait indefinitely.

Rate limiting the production health check

The Week 1 exercise rate limits /healthz only to make the behaviour visible. Do not copy that choice into a real deployment.

Knowledge assessment

Question 1 of 4

Why can a handler written using Go's standard net/http package be used directly with a chi router?

Pick an answer, then say how sure you are.

Practical applications

  • Exercise 1.19: chi server with /healthz. You will create the chi router, register the standard middleware, wire in the rate-limit middleware, configure the HTTP server, and expose the health endpoint. The exercise leaves the limiter construction and middleware wiring for you to complete.
  • Exercise 1.22: Redis fixed window and fallback. You will use request-derived contexts with short timeouts for Redis operations so dependency calls remain bounded and respond to request cancellation.

References

Everything above is explained on this page; these are where it comes from (chi v5, Go 1.2x).

Finished Lesson 1.17?