Nov 18, 20268 min read

Middleware in Go: Logging, Recovery, Auth and Rate Limits

How HTTP middleware works in Go, how to write request ID, logging and panic recovery middleware for net/http, in which order to chain them, and how Encore middleware targets endpoints by tag and reads auth data.

Illustration for Middleware in Go: Logging, Recovery, Auth and Rate Limits

Middleware in Go is a function that wraps an http.Handler and returns another one, and that single pattern covers request IDs, logging, panic recovery, authentication and rate limiting. It works with the standard library router and with chi, Gin or Echo in slightly different shapes.

It gets harder at the edges: logging the status code needs a wrapper around http.ResponseWriter that does not hide Flush or Hijack, recovery has to sit in the right place to be logged, and auth or rate limits that only apply to some routes turn into a second router to group them.

This guide writes the common middleware for net/http, explains the order to chain it in, and then shows Encore's middleware model, where middleware targets endpoints by tag and runs with the caller's auth data already resolved.

Go middleware options at a glance

Encore middlewarenet/http middleware
Signaturefunc(req middleware.Request, next middleware.Next) middleware.Responsefunc(http.Handler) http.Handler
Which routestarget=all or target=tag:admin on tagged endpointsWhatever you wrap: the whole mux or a sub-router
Request dataEndpoint, path, tags and decoded payload via req.Data()*http.Request only
Auth dataauth.UserID() and auth.Data() from the auth handlerYour own context keys
Logging and tracingBuilt in for every requestYour logging middleware
ResponseReturn Err, Payload or headers in middleware.ResponseWrite to the ResponseWriter, or wrap it

How do you write middleware with Encore?

Encore

Encore is a backend framework with built-in infrastructure, and its middleware runs on typed endpoints rather than raw HTTP handlers. Request logging and tracing are already there for every endpoint, so middleware is left for rules of your own, and it reaches them through tags: an endpoint declared with tag:admin gets every middleware whose target includes that tag.

Application code passes through Encore and infrastructure guardrails to resources provisioned in your own AWS or GCP account.

Set up the app

Get started
brew install encoredev/tap/encore &&
encore app create
Copy

Run in your terminal to get started locally.

~
$ encore app create reports-api --example=hello-world$ cd reports-api && mkdir reports

An auth handler that carries a role

Middleware can only check a role if authentication produced one. This auth handler verifies a signed bearer token and returns the user ID plus an AuthData struct. The signing key is an Encore secret:

// reports/auth.go package reports import ( "context" "crypto/hmac" "crypto/sha256" "crypto/subtle" "encoding/hex" "strconv" "strings" "time" "encore.dev/beta/auth" "encore.dev/beta/errs" ) var secrets struct { TokenHMACKey string // signs access tokens issued at login } type AuthData struct { Role string // "member" or "admin" } // AuthHandler verifies "Authorization: Bearer <user>.<role>.<unix-expiry>.<hex hmac>". // //encore:authhandler func AuthHandler(ctx context.Context, token string) (auth.UID, *AuthData, error) { unauth := &errs.Error{Code: errs.Unauthenticated, Message: "invalid token"} parts := strings.Split(token, ".") if len(parts) != 4 || secrets.TokenHMACKey == "" { return "", nil, unauth } exp, err := strconv.ParseInt(parts[2], 10, 64) if err != nil || exp < time.Now().Unix() { return "", nil, unauth } mac := hmac.New(sha256.New, []byte(secrets.TokenHMACKey)) mac.Write([]byte(strings.Join(parts[:3], "."))) if subtle.ConstantTimeCompare([]byte(parts[3]), []byte(hex.EncodeToString(mac.Sum(nil)))) != 1 { return "", nil, unauth } return auth.UID(parts[0]), &AuthData{Role: parts[1]}, nil }

Rate limit and admin middleware

RateLimit targets every endpoint in the service and counts requests per user in one-minute windows, using an integer keyspace on a cache cluster. Locally that cache runs in memory under encore run, and a deploy provisions Redis on ElastiCache or Memorystore. RequireAdmin only runs on endpoints tagged admin:

// reports/middleware.go package reports import ( "strconv" "time" "encore.dev/beta/auth" "encore.dev/beta/errs" "encore.dev/middleware" "encore.dev/storage/cache" ) var limits = cache.NewCluster("limits", cache.ClusterConfig{ EvictionPolicy: cache.AllKeysLRU, }) type window struct { UserID auth.UID Minute int64 } // requestsPerMinute counts requests per user in fixed one-minute windows. var requestsPerMinute = cache.NewIntKeyspace[window](limits, cache.KeyspaceConfig{ KeyPattern: "rl/:UserID/:Minute", DefaultExpiry: cache.ExpireIn(2 * time.Minute), }) const perMinute = 60 // RateLimit allows each signed-in user 60 requests a minute across this service. // //encore:middleware target=all func RateLimit(req middleware.Request, next middleware.Next) middleware.Response { uid, ok := auth.UserID() if !ok { return next(req) } now := time.Now() n, err := requestsPerMinute.Increment(req.Context(), window{uid, now.Unix() / 60}, 1) if err == nil && n > perMinute { resp := middleware.Response{Err: &errs.Error{Code: errs.ResourceExhausted, Message: "rate limit exceeded"}} resp.Header().Set("Retry-After", strconv.Itoa(60-now.Second())) return resp } // If the cache is unreachable this fails open; return an error instead // if a missed limit is worse than a rejected request. return next(req) } // RequireAdmin runs only on endpoints tagged "admin". // //encore:middleware target=tag:admin func RequireAdmin(req middleware.Request, next middleware.Next) middleware.Response { data, _ := auth.Data().(*AuthData) if data == nil || data.Role != "admin" { return middleware.Response{Err: &errs.Error{Code: errs.PermissionDenied, Message: "admin only"}} } return next(req) }

The endpoints only declare what they need. Delete carries tag:admin, so RequireAdmin runs before it, and both run behind RateLimit:

// reports/reports.go package reports import ( "context" "encore.dev/rlog" ) type Report struct { ID string `json:"id"` Title string `json:"title"` } type ListResponse struct { Reports []Report `json:"reports"` } //encore:api auth method=GET path=/reports func List(ctx context.Context) (*ListResponse, error) { return &ListResponse{Reports: []Report{{ID: "r1", Title: "October expenses"}}}, nil } //encore:api auth method=DELETE path=/reports/:id tag:admin func Delete(ctx context.Context, id string) error { rlog.Info("report deleted", "id", id) return nil }

Under encore run, a member token gets 200 on GET /reports and 403 admin only on DELETE /reports/r1, an admin token gets 200 on the delete, and the 61st request inside a minute returns 429 with a Retry-After header. Middleware declared in a service applies only to that service's endpoints; add the global keyword to apply it across services, and global middleware runs before service middleware.

Tags make the rule visible on the endpoint itself, which helps when a coding agent adds an endpoint: it copies tag:admin from its neighbours instead of finding the right sub-router, and the check runs locally the moment it does.

Best fit: Go backends where middleware rules depend on who is calling and which endpoint they hit, and where request logging, tracing and the Redis the limiter uses should come with the framework.

How do you write middleware for net/http?

net/http

The standard pattern is func(http.Handler) http.Handler. Logging needs the status code, which http.ResponseWriter does not expose, so a small recorder wraps the writer, and its Unwrap method keeps http.ResponseController able to reach Flush and Hijack on the original writer. Recovery re-panics on http.ErrAbortHandler, which handlers use on purpose to abort a response:

// main.go package main import ( "crypto/rand" "encoding/hex" "log/slog" "net/http" "os" "time" ) type Middleware func(http.Handler) http.Handler // Chain applies middleware so the first one listed is the outermost. func Chain(h http.Handler, mws ...Middleware) http.Handler { for i := len(mws) - 1; i >= 0; i-- { h = mws[i](h) } return h } // statusRecorder captures the status code a handler writes. type statusRecorder struct { http.ResponseWriter status int } func (r *statusRecorder) WriteHeader(code int) { r.status = code r.ResponseWriter.WriteHeader(code) } // Unwrap lets http.ResponseController reach Flush and Hijack on the original writer. func (r *statusRecorder) Unwrap() http.ResponseWriter { return r.ResponseWriter } func RequestID(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { id := r.Header.Get("X-Request-Id") if id == "" || len(id) > 64 { b := make([]byte, 8) rand.Read(b) id = hex.EncodeToString(b) } w.Header().Set("X-Request-Id", id) next.ServeHTTP(w, r) }) } func Logging(log *slog.Logger) Middleware { return func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { start := time.Now() rec := &statusRecorder{ResponseWriter: w, status: http.StatusOK} next.ServeHTTP(rec, r) log.Info("request", "method", r.Method, "path", r.URL.Path, "status", rec.status, "duration_ms", time.Since(start).Milliseconds(), "request_id", w.Header().Get("X-Request-Id")) }) } } func Recover(log *slog.Logger) Middleware { return func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { defer func() { if err := recover(); err != nil { if err == http.ErrAbortHandler { panic(err) } log.Error("panic", "err", err, "path", r.URL.Path) http.Error(w, "internal error", http.StatusInternalServerError) } }() next.ServeHTTP(w, r) }) } } func main() { log := slog.New(slog.NewJSONHandler(os.Stdout, nil)) mux := http.NewServeMux() mux.HandleFunc("GET /reports", func(w http.ResponseWriter, r *http.Request) { w.Write([]byte(`{"reports":[]}`)) }) h := Chain(mux, RequestID, Logging(log), Recover(log)) if err := http.ListenAndServe(":8080", h); err != nil { log.Error("server stopped", "err", err) } }

Order matters here. RequestID runs first so the ID exists before anything logs, Logging wraps everything below it so the duration covers the whole request, and Recover sits inside Logging, so a panicking handler is logged with status 500 rather than disappearing from the access log. The request ID is accepted from the client when present and short, which is useful for correlation and should never be trusted for anything else.

Auth and rate limits follow the same shape: auth reads the token, stores the user in the request context under an unexported key type, and returns 401 before calling next; the rate limiter reads that user and needs a shared store such as Redis once more than one instance runs. Routes that need an extra check get their own sub-router or a per-route wrapper, for example mux.Handle("DELETE /reports/{id}", RequireAdmin(http.HandlerFunc(deleteReport))).

Best fit: services built directly on net/http, or on routers like chi that accept the same middleware signature, where you want full control of every layer.

How to choose

Pick Encore when the middleware you need is about the caller and the endpoint, such as roles, tenants and rate limits, and you want logging, tracing and the cache behind the limiter to come with the framework and run locally under encore run. Pick plain net/http middleware when you are extending an existing standard library or chi service, and keep the order request ID, logging, recovery, then auth and limits.

Frequently asked questions

How do you write middleware in Go?

Write a function that takes an http.Handler and returns a new http.Handler. The returned handler runs code before and after calling next.ServeHTTP(w, r), and you wrap the router with it, for example Chain(mux, RequestID, Logging(log), Recover(log)).

How do I log the status code in Go middleware?

Wrap the http.ResponseWriter in a struct that records the code passed to WriteHeader, defaulting to 200, and pass that wrapper to the next handler. Add an Unwrap method that returns the original writer so http.ResponseController can still reach Flush and Hijack.

In which order should Go middleware run?

Put the request ID first so every later log line can include it, logging next so it measures the full request, and panic recovery inside logging so a recovered panic is logged with its 500 status. Authentication and rate limits come after that, closest to the handlers they protect.

How does middleware work in Encore for Go?

Declare a function with //encore:middleware and a target, either target=all or a list of tags such as target=tag:admin. It receives a middleware.Request with the endpoint, path and decoded payload, calls next to run the handler, and can return a middleware.Response with an error or headers. Middleware declared without the global keyword applies only to endpoints in its own service.

Deploy to your cloud on AWS and Google Cloud
without managing infrastructure

Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.

~/orders — claude
Claude Code
Claude Code v2.1.180Opus 5.5~/orders