typestar

Middleware in Go

A middleware takes a handler and returns one that wraps it.

type recorder struct {
    http.ResponseWriter
    status int
}

func (r *recorder) WriteHeader(code int) {
    r.status = code
    r.ResponseWriter.WriteHeader(code)
}

func withLogging(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        started := time.Now()
        wrapped := &recorder{ResponseWriter: w, status: http.StatusOK}
        next.ServeHTTP(wrapped, r)
        slog.Info("request", "method", r.Method, "path", r.URL.Path,
            "status", wrapped.status, "took", time.Since(started))
    })
}

func chain(handler http.Handler) http.Handler {
    return withLogging(handler)
}

How it works

  1. The signature is func(http.Handler) http.Handler.
  2. They compose by nesting, outermost last.
  3. A response wrapper is how you capture the status code.

Keywords and builtins used here

The run, in numbers

Lines
23
Characters to type
587
Tokens
153
Three-star pace
110 tpm

At the three-star pace of 110 tokens a minute, this run takes about 83 seconds.

Type this snippet

Step 3 of 5 in HTTP, step 18 of 26 in Standard library & project layout.

← Previous Next →

Middleware in other languages