net/http handlers and middleware

How a Go HTTP server turns a request into a call to a handler, what the ResponseWriter and Request give you, and how middleware wraps a handler to add behaviour such as rate limiting.

Learning outcomes

  • Write an http.Handler and an http.HandlerFunc and register them on a mux.
  • Read the method, path, headers and remote address from *http.Request.
  • Write status, headers and a JSON body with http.ResponseWriter, in the right order.
  • Write middleware as a function from handler to handler and chain several.
  • Test a handler with net/http/httptest without opening a port.
  • Configure http.Server timeouts and explain why they matter.

From an incoming request to Go code

A backend server receives HTTP requests from clients such as mobile apps, browsers, and other services. It must inspect each request, decide what to do, and send an HTTP response.

In Go, the standard library provides the net/http package for this work. You do not need a web framework to build a working HTTP server.

The central building block is an HTTP handler. A handler is a value that knows how to process an HTTP request and write its response.

In this lesson, you will build handlers, register them on a ServeMux, write middleware, choose a rate-limit identity key, and test everything without opening a network port. The examples use the Limiter interface introduced earlier:

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

The interface is deliberately small. The HTTP layer does not need to know whether the limiter uses a token bucket, a fixed window, or another algorithm. It only needs to ask whether a request is allowed.

How Go handles an HTTP request

An HTTP server listens for incoming connections. When a client sends a request, the server parses the HTTP message and creates an *http.Request representing it.

The server then routes the request to a handler. The handler examines the request and writes a response through an http.ResponseWriter.

The standard HTTP server can process multiple requests concurrently. In normal server operation, each incoming request is handled in its own goroutine. This means two requests can call the same handler at nearly the same time.

That has an important consequence for your backend: handlers must be safe for concurrent use. If they share mutable state, that state needs appropriate synchronisation. Your rate limiter already uses a mutex to protect its shared state.

A request does not automatically correspond to a new process or a new server instance. The same handler value can be reused for many requests.

Writing an HTTP handler

The net/http package defines the http.Handler interface:

go
type Handler interface {
	ServeHTTP(ResponseWriter, *Request)
}

Any type with a method matching this signature implements http.Handler.

The two parameters are:

  • http.ResponseWriter: the destination for the HTTP response.
  • *http.Request: the incoming HTTP request, including its method, URL, headers, body, and connection information.

Here is a complete handler type:

go
package main

import (
	"fmt"
	"net/http"
)

type HealthHandler struct{}

func (h HealthHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintln(w, "ok")
}

func main() {
	handler := HealthHandler{}
	http.ListenAndServe(":8080", handler)
}

The HealthHandler type implements http.Handler because it has the required ServeHTTP method.

When a request reaches this handler, it writes ok followed by a newline to the response body.

The HandlerFunc adapter

Defining a new type for every small handler can become repetitive. Go provides http.HandlerFunc, a function type that adapts an ordinary function into an http.Handler.

Its relevant definition is:

go
type HandlerFunc func(ResponseWriter, *Request)

func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) {
	f(w, r)
}

You usually do not need to write this adapter yourself. Use it like this:

go
package main

import (
	"fmt"
	"net/http"
)

func healthHandler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintln(w, "ok")
}

func main() {
	http.ListenAndServe(":8080", http.HandlerFunc(healthHandler))
}

The function healthHandler does not have a ServeHTTP method. Converting it to http.HandlerFunc gives it one through the adapter.

This is why you will commonly see handlers written as ordinary functions rather than custom types.

Registering handlers with ServeMux

A multiplexer, or mux, matches an incoming request to a handler based on its URL path and, depending on the pattern, its HTTP method.

The standard library provides http.ServeMux.

go
package main

import (
	"fmt"
	"net/http"
)

func healthHandler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintln(w, "ok")
}

func restaurantsHandler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintln(w, "restaurants")
}

func main() {
	mux := http.NewServeMux()

	mux.HandleFunc("/healthz", healthHandler)
	mux.HandleFunc("/restaurants", restaurantsHandler)

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

The mux itself implements http.Handler. The server calls its ServeHTTP method, and the mux selects the registered handler.

For this course, the API server will eventually use a router from the chi package. That comes in the next lesson. The underlying handler and middleware concepts remain the same because chi handlers use the standard net/http interfaces.

Reading an HTTP request

The request object contains the information your handler needs to make decisions.

Method and URL path

The HTTP method describes the operation the client wants to perform. Common methods include:

  • GET to retrieve a resource.
  • POST to submit data or create a resource.
  • PUT to replace a resource.
  • PATCH to partially update a resource.
  • DELETE to remove a resource.

Read the method and path from the request:

go
func inspectHandler(w http.ResponseWriter, r *http.Request) {
	method := r.Method
	path := r.URL.Path

	fmt.Fprintf(w, "method=%s path=%s\n", method, path)
}

The URL path does not include the query string.

Query parameters

A query parameter is a key-value pair in the URL after the ? character.

For example:

GET /v1/restaurants?limit=20&cursor=abc

Read query parameters through r.URL.Query():

go
func listRestaurantsHandler(w http.ResponseWriter, r *http.Request) {
	query := r.URL.Query()

	limit := query.Get("limit")
	cursor := query.Get("cursor")

	fmt.Fprintf(w, "limit=%s cursor=%s\n", limit, cursor)
}

Get returns an empty string when a parameter is missing. If the parameter is numeric, parse it and handle invalid input rather than assuming it is valid.

Headers

HTTP headers carry metadata about a request or response. Examples include Content-Type, Authorization, and X-User-ID.

Read a request header using Header.Get:

go
func inspectHeadersHandler(w http.ResponseWriter, r *http.Request) {
	contentType := r.Header.Get("Content-Type")
	userID := r.Header.Get("X-User-ID")

	fmt.Fprintf(w, "content-type=%s user-id=%s\n", contentType, userID)
}

Header names are case-insensitive according to HTTP. Go canonicalises header names when using methods such as Header.Set and Header.Get.

Prefer these methods instead of directly manipulating the underlying header map:

go
w.Header().Set("Content-Type", "application/json")

Direct map access can introduce inconsistent key casing and is unnecessary for ordinary HTTP code.

Remote address

The request also contains r.RemoteAddr, which represents the network address of the connection's peer. It commonly includes both a host and a port:

192.0.2.10:54321

You can separate them with net.SplitHostPort:

go
package main

import (
	"fmt"
	"net"
)

func clientIP(remoteAddr string) string {
	host, _, err := net.SplitHostPort(remoteAddr)
	if err != nil {
		return remoteAddr
	}

	return host
}

func main() {
	fmt.Println(clientIP("192.0.2.10:54321"))
}

This returns the host portion without the port. The fallback returns the original value when the address cannot be split.

Choosing a rate-limit identity key

A rate limiter needs a key that identifies which client or group of clients should share a limit. This is the identity key.

For a food delivery backend, you might eventually limit requests by authenticated user. For unauthenticated requests, you may use the client's IP address.

For this week's exercises, use this rule:

  1. If X-User-ID is present, use its value.
  2. Otherwise, extract the host from r.RemoteAddr and use that as the key.

Here is a helper:

go
package httpx

import "net"

func IdentityKey(remoteAddr, userID string) string {
	if userID != "" {
		return userID
	}

	host, _, err := net.SplitHostPort(remoteAddr)
	if err != nil {
		return remoteAddr
	}

	return host
}

The helper accepts the values as arguments so it can be tested independently of an HTTP request.

The trust boundary

A client can send arbitrary HTTP headers. That includes X-User-ID.

If your server accepts this header directly from an untrusted client, the client can claim to be another user. That could let someone bypass a per-user rate limit by changing the header.

In this course, X-User-ID is a teaching stand-in for a trusted identity that will arrive through authentication in Week 3. Do not treat it as proof of identity in a production system.

The same concern applies to X-Forwarded-For. This header can contain an IP address supplied by the client. It is only trustworthy when your infrastructure has a trusted reverse proxy that controls how the header is set or sanitised, and your application accepts it only from that proxy.

For now, use RemoteAddr as the fallback. It identifies the direct network peer connected to your server. If your server is behind a reverse proxy, that peer may be the proxy rather than the original client. Handling trusted proxy configuration is an explicit infrastructure decision, not something to solve by blindly trusting a request header.

Identity selection

Show a request entering an identity-key helper: if X-User-ID is present, use its value; otherwise split RemoteAddr and use only the host; show X-Forwarded-For arriving from the client as untrusted unless a trusted reverse proxy controls it.Show a request entering an identity-key helper: if X-User-ID is present, use its value; otherwise split RemoteAddr and use only the host; show X-Forwarded-For arriving from the client as untrusted unless a trusted reverse proxy controls it.

Writing an HTTP response correctly

The http.ResponseWriter is how a handler sends the response to the client.

A response contains a status code, headers, and an optional body. The order in which you write them matters.

The normal sequence is:

  1. Set response headers.
  2. Write the status code with WriteHeader.
  3. Write the response body.

For example:

go
func healthHandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "text/plain; charset=utf-8")
	w.WriteHeader(http.StatusOK)
	fmt.Fprintln(w, "ok")
}

If you do not call WriteHeader, the first call to Write or a helper that writes a body sends 200 OK automatically.

Once the response has been committed, changing its headers or status code has no effect on the response already sent. This is why you must set headers before writing the body.

Do not try to write two different responses to one request. For example, after writing a rejection response, return from the handler or middleware. Continuing to write another status or body can produce a confusing response and log warnings.

Status code constants

The net/http package provides named constants for standard HTTP status codes.

For example:

  • http.StatusOK is 200.
  • http.StatusBadRequest is 400.
  • http.StatusUnauthorized is 401.
  • http.StatusTooManyRequests is 429.
  • http.StatusInternalServerError is 500.

Prefer these constants over unexplained numeric literals.

http.Error versus a custom JSON error

For a small plain-text error response, http.Error is convenient:

go
func exampleHandler(w http.ResponseWriter, r *http.Request) {
	http.Error(w, "request failed", http.StatusBadRequest)
}

It writes a plain-text response and sets an appropriate content type. It also writes the status code.

A JSON API often needs a consistent error shape. In that case, write a JSON response yourself.

JSON encoding and decoding

JSON is a text format commonly used to exchange structured data between a mobile app and a backend. Go's standard encoding/json package converts between Go values and JSON.

This is JSON encoding.

Encoding a response

Use json.NewEncoder(w).Encode(value) to encode a Go value directly into the response writer.

go
package main

import (
	"encoding/json"
	"net/http"
)

type ErrorResponse struct {
	Error string `json:"error"`
}

func writeJSON(w http.ResponseWriter, status int, value any) {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(status)

	if err := json.NewEncoder(w).Encode(value); err != nil {
		return
	}
}

func exampleHandler(w http.ResponseWriter, r *http.Request) {
	writeJSON(w, http.StatusBadRequest, ErrorResponse{
		Error: "invalid request",
	})
}

func main() {
	http.ListenAndServe(":8080", http.HandlerFunc(exampleHandler))
}

The json struct tag controls the JSON field name. The Error field is encoded as error.

Encode writes the JSON value followed by a newline. It can return an error, for example if the value cannot be encoded. Once the response has started, an encoding error cannot reliably be turned into a different HTTP status response. In production code, validate or prepare data before committing the response when possible, and log failures that occur during response writing.

Decoding a request body

A client may send JSON in a POST request body. Decode it with json.NewDecoder.

go
package main

import (
	"encoding/json"
	"net/http"
)

type CreateRestaurantRequest struct {
	Name string `json:"name"`
}

func createRestaurantHandler(w http.ResponseWriter, r *http.Request) {
	var input CreateRestaurantRequest

	if err := json.NewDecoder(r.Body).Decode(&input); err != nil {
		http.Error(w, "invalid JSON body", http.StatusBadRequest)
		return
	}

	if input.Name == "" {
		http.Error(w, "name is required", http.StatusBadRequest)
		return
	}

	w.WriteHeader(http.StatusCreated)
}

Always handle decoding errors. Never assume the request body contains valid JSON or the fields your application requires.

The HTTP server closes the request body when the request has been fully processed. Handlers generally do not need to close r.Body themselves. If your handler reads only part of a body, consider the implications for connection reuse and request processing. For ordinary request handling, consume the body as needed and let the server manage its lifecycle.

What middleware does

HTTP middleware is a function that wraps an HTTP handler to add behaviour before or after the handler runs.

Middleware is useful for concerns that apply to many routes, such as logging, authentication, request IDs, and rate limiting.

The standard middleware function shape is:

go
func(http.Handler) http.Handler

It accepts the next handler in the chain and returns a new handler.

A simple logging middleware looks like this:

go
package main

import (
	"log"
	"net/http"
)

func loggingMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		log.Printf("method=%s path=%s", r.Method, r.URL.Path)
		next.ServeHTTP(w, r)
	})
}

The middleware logs the request and then calls next.ServeHTTP. That call passes control to the next handler in the chain.

If middleware does not call next.ServeHTTP, the chain stops there. This is how middleware can reject a request before it reaches the route handler.

Chaining middleware

Suppose you have three middleware functions:

  • Logging records request information.
  • Authentication checks the client's identity.
  • Rate limiting decides whether the request can continue.

The request enters the outer middleware first. Each middleware can perform work before calling the next handler. After the innermost handler finishes, control returns through the middleware layers in reverse order.

Show a request passing through logging, authentication, and rate-limit middleware before reaching a handler, with the response travelling back through the layers; also show rate-limit middleware rejecting a request with 429 and returning without calling the next handler.Show a request passing through logging, authentication, and rate-limit middleware before reaching a handler, with the response travelling back through the layers; also show rate-limit middleware rejecting a request with 429 and returning without calling the next handler.

Order matters. If rate limiting is placed after expensive application work, the server has already spent resources before deciding to reject the request. Put the limiter before the work it is meant to protect.

Middleware can also recover from panics. A recovery middleware catches a panic in a downstream handler and turns it into a controlled server error rather than allowing the request goroutine to terminate unexpectedly. Recovery is normally placed outside the handlers it should protect.

Building simplified rate-limit middleware

The middleware will depend on the Limiter interface:

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

It also needs a function that extracts the identity key from the request.

For this lesson, we will keep the implementation deliberately small. It demonstrates the control flow and response shape, but it is not the complete exercise solution.

First, define a fake limiter for tests:

go
package httpx

type fakeLimiter struct {
	allowed bool
}

func (f fakeLimiter) Allow(key string) bool {
	return f.allowed
}

Now define the middleware:

go
package httpx

import (
	"encoding/json"
	"net/http"
	"strconv"
)

type Limiter interface {
	Allow(key string) bool
}

type RateLimitError struct {
	Error string `json:"error"`
}

func RateLimit(limiter Limiter, retryAfter int) func(http.Handler) http.Handler {
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			key := IdentityKey(r.RemoteAddr, r.Header.Get("X-User-ID"))

			if !limiter.Allow(key) {
				w.Header().Set("Content-Type", "application/json")
				w.Header().Set("Retry-After", strconv.Itoa(retryAfter))
				w.WriteHeader(http.StatusTooManyRequests)

				_ = json.NewEncoder(w).Encode(RateLimitError{
					Error: "rate limit exceeded",
				})
				return
			}

			next.ServeHTTP(w, r)
		})
	}
}

Read the control flow carefully:

  1. The middleware receives the next handler.
  2. It returns a handler that can inspect each request.
  3. It builds the identity key.
  4. It asks the limiter whether the request is allowed.
  5. If rejected, it writes a 429 response and returns.
  6. If allowed, it calls next.ServeHTTP.

The return is essential. Without it, the request could continue to the route handler after receiving a rejection response.

Retry-After tells the client how long to wait before retrying. Its value is a string, so strconv.Itoa converts the integer number of seconds into a string.

This example accepts a fixed retry delay to keep the middleware's responsibilities clear. A real limiter may need to calculate a more accurate retry duration.

Registering the middleware

You can wrap a handler directly:

go
package main

import (
	"fmt"
	"net/http"
)

type fakeLimiter struct {
	allowed bool
}

func (f fakeLimiter) Allow(key string) bool {
	return f.allowed
}

func healthHandler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintln(w, "ok")
}

func main() {
	mux := http.NewServeMux()
	mux.HandleFunc("/healthz", healthHandler)

	limiter := fakeLimiter{allowed: true}
	handler := RateLimit(limiter, 30)(mux)

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

The outer rate-limit handler receives requests before the mux. This means every route registered on that mux passes through the middleware.

In the actual course exercises, you will apply the middleware to the required server routes and use the supplied limiter implementation. The code above only demonstrates how the pieces fit together.

Testing handlers and middleware without opening a port

You do not need to start a real HTTP server to test a handler. The net/http/httptest package provides tools for constructing requests and recording responses in memory.

The most useful pieces are:

  • httptest.NewRequest or httptest.NewRequestWithContext creates a request.
  • httptest.NewRecorder creates a response recorder.
  • handler.ServeHTTP(recorder, request) invokes the handler directly.
  • recorder.Result() returns the recorded HTTP response.

This is faster and more reliable than opening a port for every handler test.

Testing a handler

Here is a test for a simple JSON handler:

go
package httpx

import (
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"testing"
)

func TestWriteJSONHandler(t *testing.T) {
	handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(http.StatusOK)
		_ = json.NewEncoder(w).Encode(map[string]string{
			"status": "ok",
		})
	})

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

	handler.ServeHTTP(rec, req)

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

	if got := rec.Header().Get("Content-Type"); got != "application/json" {
		t.Fatalf("content type = %q, want application/json", got)
	}
}

The recorder captures the status, headers, and response body. The test checks the externally visible HTTP behaviour rather than the internal implementation.

httptest.NewRequestWithContext is another option when you need to provide a specific request context. You will learn more about request contexts in the next lesson.

Testing middleware rejection

A middleware test should verify both that the response is correct and that the downstream handler was not called.

go
package httpx

import (
	"net/http"
	"net/http/httptest"
	"testing"
)

func TestRateLimitRejectsRequest(t *testing.T) {
	limiter := fakeLimiter{allowed: false}

	called := false
	next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		called = true
	})

	handler := RateLimit(limiter, 30)(next)

	req := httptest.NewRequest(http.MethodGet, "/restaurants", nil)
	req.RemoteAddr = "192.0.2.10:12345"

	rec := httptest.NewRecorder()
	handler.ServeHTTP(rec, req)

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

	if got := rec.Header().Get("Retry-After"); got != "30" {
		t.Fatalf("Retry-After = %q, want 30", got)
	}

	if called {
		t.Fatal("next handler was called after rejection")
	}
}

This test uses a fake limiter that always rejects. That isolates the HTTP middleware from the actual rate-limiting algorithm.

You should also test the allowed path, where the middleware calls the next handler. Together, these tests verify that middleware both rejects and forwards requests correctly.

A response recorder wrapper can be useful when middleware needs to observe details such as the status code written by a downstream handler. That is an additional technique, not something you need to implement for this lesson.

Configuring the HTTP server safely

A server that accepts network connections should not use an entirely unconfigured http.Server in production.

Some clients may connect and send headers extremely slowly. Without timeouts, a server can keep connections and resources occupied for too long. This kind of behaviour can contribute to slow-client attacks.

Configure the server explicitly:

go
package main

import (
	"log"
	"net/http"
	"time"
)

func main() {
	mux := http.NewServeMux()
	mux.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusOK)
	})

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

	log.Fatal(server.ListenAndServe())
}

These fields control different parts of a connection's lifetime:

  • ReadHeaderTimeout limits how long the server waits to read request headers.
  • ReadTimeout limits the time allowed to read the entire request, including its body.
  • WriteTimeout limits the time allowed to write a response.
  • IdleTimeout controls how long a keep-alive connection can remain idle while waiting for another request.

The zero value for these timeout fields means no timeout is configured for that setting. Leaving them at zero can allow slow clients to occupy connections for an unnecessarily long time.

The values above are teaching examples, not universal production settings. Real timeout values depend on request sizes, upload behaviour, network conditions, and the operations your API performs.

Common mistakes to avoid

Writing the body before setting headers

The first body write implicitly sends 200 OK. Set headers and the intended status before writing the body.

Continuing after rejecting a request

If middleware writes a 429 response, return immediately. Do not call the next handler.

Trusting arbitrary identity headers

A client can forge X-User-ID or X-Forwarded-For. Only trust identity information established by a trusted authentication layer or a correctly configured proxy.

Putting rate limiting after expensive work

The middleware must run before the application work it is intended to protect. Otherwise, rejected requests still consume those resources.

Writing more than one response

Once a response is committed, you cannot replace it with another status code. Return after writing an error response.

Ignoring request body errors

JSON decoding can fail because the body is empty, malformed, or does not match the expected input. Handle the error and reject invalid requests.

Leaving server timeouts at zero

An HTTP server with no relevant timeouts can leave resources occupied by slow clients. Configure timeouts deliberately.

Knowledge assessment

Question 1 of 4

What is the relationship between http.Handler and http.HandlerFunc in Go?

Pick an answer, then say how sure you are.

Practical applications

  • Exercise 1.18: RateLimit middleware that returns 429. You will implement middleware around the Limiter interface, choose an identity key, reject requests with a JSON error response, and include Retry-After.
  • Exercise 1.19: The chi server. You will use the standard HTTP handler and middleware interfaces with chi, register routes, and build the API server.

References

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

Finished Lesson 1.16?