Gin foundations · 5 MIN READ

Writing Gin middleware: what c.Next returns to, what Abort does not do, and typed request values

Write Gin middleware that runs code after c.Next, stops the chain with Abort and return, shares typed values through c.Set and c.Get, and is ordered so logs see the final outcome.

Gin middleware is an ordinary handler that happens to run before others in the same chain. Most middleware bugs come from a wrong mental model of that chain: expecting Abort to return, expecting a middleware without c.Next to stop the request, or reading a status before the handler has chosen it. This lesson builds four realistic middleware functions and traces exactly what runs.

gin · A MAP OF THE IDEA

  1. Set headers before Next
  2. Abort, then return
  3. Read outcome after Next
  4. Order observers outermost

Useful when

  • Post-Next code observes status, errors and abort state for every request.
  • Typed keys and accessors make request values collision-free and explicit.

Watch out

  • c.Value ignores non-string keys stored with c.Set.
  • With Recovery outermost, panicking requests leave no access-log line.

Implementation & operation cost: A few small functions and one ordering decision per engine; the per-request overhead is a slice index and a map write per value.

01

The chain is one loop over a slice

For a matched route Gin stores one slice of handlers: engine middleware from r.Use, then group middleware, then the handlers passed to the route, in registration order. Serving a request calls c.Next once, which runs the slice in a loop. When a handler calls c.Next itself, the remaining handlers run inside that call and control comes back afterwards; when it returns without calling c.Next, the outer loop simply continues with the next handler. So c.Next is needed only when you want code to run after the rest of the chain. c.Abort sets the chain index to a sentinel so every loop stops, and c.IsAborted reports whether that happened. Abort does not return from the current function and does not undo anything already written.

02

An access log, a request ID and two guards

The program registers an access log and a request-ID middleware globally, an authentication guard on two routes and a role guard on one of them. Each middleware appends to a trace, so every response line shows which functions ran and in what order. The access-log lines printed at the end show what the outermost middleware can observe after c.Next.

go
package main

import (
	"fmt"
	"net/http"
	"net/http/httptest"
	"strings"

	"github.com/gin-gonic/gin"
)

// ctxKey is unexported, so no other package can collide with these keys.
type ctxKey int

const (
	requestIDKey ctxKey = iota
	userKey
)

type user struct {
	ID   string
	Role string
}

var trace []string

func accessLog(lines *[]string) gin.HandlerFunc {
	return func(c *gin.Context) {
		trace = append(trace, "log>")
		c.Next() // everything below runs after the rest of the chain
		trace = append(trace, "<log")
		route := c.FullPath()
		if route == "" {
			route = "unmatched"
		}
		*lines = append(*lines, fmt.Sprintf("id=%s %s %s status=%d aborted=%t",
			c.GetString(requestIDKey), c.Request.Method, route, c.Writer.Status(), c.IsAborted()))
	}
}

func requestID(next func() string) gin.HandlerFunc {
	return func(c *gin.Context) {
		id := c.GetHeader("X-Request-Id")
		if id == "" || len(id) > 64 {
			id = next()
		}
		c.Set(requestIDKey, id)
		c.Header("X-Request-Id", id)
		trace = append(trace, "id")
		// No c.Next(): Gin continues the chain when this function returns.
	}
}

func requireUser(c *gin.Context) {
	tokens := map[string]user{"t-user": {ID: "u-1", Role: "member"}, "t-admin": {ID: "u-2", Role: "admin"}}
	u, ok := tokens[strings.TrimPrefix(c.GetHeader("Authorization"), "Bearer ")]
	if !ok {
		trace = append(trace, "user:abort")
		c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "unauthenticated"})
		return // Abort stops later handlers, return stops this one
	}
	trace = append(trace, "user")
	c.Set(userKey, u)
}

func requireRole(role string) gin.HandlerFunc {
	return func(c *gin.Context) {
		if currentUser(c).Role != role {
			trace = append(trace, "role:abort")
			c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": "forbidden"})
			return
		}
		trace = append(trace, "role")
	}
}

// currentUser is only called behind requireUser, so a missing key is a wiring bug.
func currentUser(c *gin.Context) user {
	return c.MustGet(userKey).(user)
}

func main() {
	gin.SetMode(gin.TestMode)
	var lines []string
	n := 0
	r := gin.New()
	r.Use(accessLog(&lines), requestID(func() string { n++; return fmt.Sprintf("req-%d", n) }))
	r.GET("/health", func(c *gin.Context) { trace = append(trace, "health"); c.Status(http.StatusOK) })
	r.GET("/me", requireUser, func(c *gin.Context) {
		trace = append(trace, "me")
		c.JSON(http.StatusOK, gin.H{"id": currentUser(c).ID})
	})
	r.DELETE("/users/:id", requireUser, requireRole("admin"), func(c *gin.Context) {
		trace = append(trace, "delete")
		c.Status(http.StatusNoContent)
	})

	for _, tc := range []struct{ method, path, token, reqID string }{
		{"GET", "/health", "", ""},
		{"GET", "/me", "", ""},
		{"GET", "/me", "t-user", "client-7"},
		{"DELETE", "/users/9", "t-user", ""},
		{"DELETE", "/users/9", "t-admin", ""},
		{"GET", "/missing", "", ""},
	} {
		trace = nil
		req := httptest.NewRequest(tc.method, tc.path, nil)
		if tc.token != "" {
			req.Header.Set("Authorization", "Bearer "+tc.token)
		}
		if tc.reqID != "" {
			req.Header.Set("X-Request-Id", tc.reqID)
		}
		w := httptest.NewRecorder()
		r.ServeHTTP(w, req)
		fmt.Println(tc.method, tc.path, w.Code, trace)
	}
	for _, line := range lines {
		fmt.Println(line)
	}
}
Read the code

accessLog wraps everything: "log>" is recorded before c.Next and "<log" after it, even for the aborted requests and the 404, because aborting stops later handlers but returns control to earlier ones. requestID never calls c.Next, yet the chain continues. requireUser aborts with 401 and returns, so neither "me" nor the role check runs. On the DELETE with a member token the role guard aborts with 403. After c.Next the log reads the request ID set by an inner middleware, the template from FullPath, the final status and IsAborted. The unmatched request runs only engine middleware, which is why its trace has no guards.

03

Code after Next sees the outcome, not the bytes on the wire

After c.Next returns, c.Writer.Status() holds the status the chain chose, which is 200 if nobody set one, so a handler that writes nothing still logs as 200. c.Writer.Written() and c.Writer.Size() tell you whether a body was written; Size is -1 when nothing was, because Gin flushes the final header only after the whole chain returns. c.Errors holds errors attached with c.Error. It is too late to change headers once the body is written, so set response headers such as X-Request-Id before c.Next, as requestID does. Panics skip the code after c.Next unless a recovery runs inside you: with accessLog registered before gin.Recovery(), the log sees the 500 that Recovery writes; with the order reversed the log line for a panicking request is simply missing.

04

Typed keys for c.Set and c.Get

In v1.12.0 c.Keys is a map[any]any protected by a mutex, and Set, Get and MustGet take a key of type any. Use an unexported key type, as with context.WithValue, so two packages cannot overwrite each other's "user". Wrap reads in a typed accessor such as currentUser. MustGet panics with "key ... does not exist", which is right when a missing value means the route was wired without its guard; use Get and its ok flag for optional values. One trap: *gin.Context implements context.Context, but its Value method looks in Keys only for string keys, so c.Value(userKey) returns nil here and then falls back to the request context only if engine.ContextWithFallback is set. Pass the user to services as an argument, or attach it with c.Request.WithContext. Keys are cleared when the context returns to Gin's pool, so never keep them past the handler; the context-workers lesson covers that boundary.

05

Choose where each middleware lives

Engine-level middleware runs for every request, including 404 and 405 responses, so it is the place for access logs, metrics, request IDs and recovery. Group middleware suits authentication for an area of the API. Per-route middleware suits authorization and endpoint-specific policies such as a body limit or an idempotency check. Order them so observers wrap actors: logging and metrics outermost, recovery inside them, request ID before anything that logs, authentication before authorization.

go
r := gin.New()
// Outermost first: the log observes the 500 that Recovery writes.
r.Use(accessLog(logger), gin.Recovery(), requestID(newID))

api := r.Group("/api", requireUser)                        // authentication per area
api.GET("/me", me)                                         // any signed-in user
api.DELETE("/users/:id", requireRole("admin"), deleteUser) // authorization per route
Read the code

This fragment shows the layering with placeholder constructors. The access log is outermost so it records every status, including the 500 from a recovered panic. requireUser guards the whole /api group, and requireRole("admin") runs only for the DELETE route, after authentication has stored the user.

06

Test middleware as part of a chain

Build a tiny engine with the middleware under test and a probe handler that records it ran. Assert the status, the headers, whether the probe ran, and what an outer recording middleware observed. Cover every abort path, a panic behind the recovery, and hostile input: a client-supplied X-Request-Id flows into your logs, so cap its length as the program does and restrict its characters before trusting it.

TAKE THIS WITH YOU

Call c.Next only when you need to run code afterwards, follow every Abort with return, read the outcome after Next from c.Writer and c.Errors, and share request values through typed keys and accessors.

Check your understanding

A middleware sets a header and returns without calling c.Next(). What happens to the rest of the chain?

Go to the source

Progress stays in this browser. No account needed.