Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 39 ยท Middleware

Writing Custom Middleware in Gin

Write your own Gin middleware using the closure pattern, request IDs, API-key authentication, passing values with c.Set, middleware with options, testing it, and runnable net/http stand-ins for each idea.

Gin's built-in middleware covers logging and panic recovery, but real applications need more: a request ID on every response, an API-key or token check, a per-request timeout, a tenant lookup. Writing middleware in Gin is pleasantly simple because it is just a function. This lesson gives you the standard pattern and four practical examples, building on Middleware Basics and Logger and Recovery.

Gin does not run on this site, so Gin code is read-only. The runnable stand-ins use net/http and show the same behavior: ordering, aborting and passing values.

The pattern: a function that returns a handler

A middleware is a gin.HandlerFunc. Define a constructor that returns it. The outer function receives configuration; the inner function (a closure) runs per request:

Go
func SecurityHeaders() gin.HandlerFunc {
	return func(c *gin.Context) {
		h := c.Writer.Header()
		h.Set("X-Content-Type-Options", "nosniff")
		h.Set("X-Frame-Options", "DENY")
		h.Set("Referrer-Policy", "strict-origin-when-cross-origin")
		c.Next()
	}
}

r.Use(SecurityHeaders())

Why a constructor, even when there is no configuration? Convention (it reads r.Use(Timing()) everywhere) and room to grow: adding a parameter later does not change the call style. Anything expensive, like compiling a regular expression or building a lookup map, belongs in the outer function so it runs once, not on every request.

Example 1: request IDs

An ID that follows a request through logs and error responses makes debugging dramatically easier. Honor an incoming ID if a proxy set one, otherwise create it:

Go
const RequestIDKey = "request_id"

func RequestID() gin.HandlerFunc {
	return func(c *gin.Context) {
		id := c.GetHeader("X-Request-Id")
		if id == "" || len(id) > 64 {
			id = newID() // e.g. 16 random bytes in hex
		}
		c.Set(RequestIDKey, id)
		c.Header("X-Request-Id", id)
		c.Next()
	}
}

Limit the length of an incoming ID and keep it to safe characters; otherwise a client can inject junk (or very long text) into your logs.

Example 2: API-key authentication

Go
func APIKey(valid map[string]string) gin.HandlerFunc { // key -> client name
	return func(c *gin.Context) {
		key := c.GetHeader("X-API-Key")
		name, ok := valid[key]
		if !ok {
			c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
				"error": gin.H{"code": "unauthorized", "message": "invalid or missing API key"},
			})
			return
		}
		c.Set("client", name)
		c.Next()
	}
}

Real keys must be compared in constant time (crypto/subtle.ConstantTimeCompare on hashes) and stored hashed. We return to authentication properly in the security chapter; here the goal is the middleware shape.

Example 3: a timing and slow-request log

Go
func SlowLog(threshold time.Duration) gin.HandlerFunc {
	return func(c *gin.Context) {
		start := time.Now()
		c.Next()
		if d := time.Since(start); d > threshold {
			log.Printf("SLOW %s %s %s status=%d", c.Request.Method, c.FullPath(), d, c.Writer.Status())
		}
	}
}

c.FullPath() returns the route pattern (/books/:id) rather than the actual URL, which keeps log lines groupable and prevents ids from exploding your metrics.

Example 4: middleware with options

When there are several settings, use a config struct (or functional options) with sensible defaults:

Go
type CORSConfig struct {
	AllowOrigins []string
	AllowMethods []string
	MaxAge       time.Duration
}

func CORS(cfg CORSConfig) gin.HandlerFunc {
	allowed := make(map[string]bool, len(cfg.AllowOrigins))
	for _, o := range cfg.AllowOrigins {
		allowed[o] = true
	}
	methods := strings.Join(cfg.AllowMethods, ", ")
	return func(c *gin.Context) {
		if origin := c.GetHeader("Origin"); allowed[origin] {
			c.Header("Access-Control-Allow-Origin", origin)
			c.Header("Vary", "Origin")
		}
		if c.Request.Method == http.MethodOptions {
			c.Header("Access-Control-Allow-Methods", methods)
			c.AbortWithStatus(http.StatusNoContent)
			return
		}
		c.Next()
	}
}

Note how the lookup map is built once in the constructor. For full CORS handling use the maintained gin-contrib/cors package; see CORS, CSRF and Security Headers.

Reading values in handlers

Values stored with c.Set are read with c.Get. To avoid string typos and repeated type assertions, wrap them:

Go
func CurrentClient(c *gin.Context) string {
	return c.GetString("client")
}

If the value is a struct, c.MustGet("user").(*User) panics when the middleware was not installed, which is a useful loud failure during development.

Stand-in: request ID, API key and values

This runnable program builds the same three middleware with net/http. Request values travel in the request context, the standard library's counterpart of c.Set. IDs come from a counter so the output is stable.

Go Stand-in: request ID and API-key middleware

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The failed request still gets an ID because requestID is the outer middleware. If you swapped the order, the 401 would carry no ID, a good example of why order matters.

Stand-in: measuring and short-circuiting

The second program shows two behaviors at once: a middleware that counts requests per client and refuses the third (a very small rate limiter), and one that adds a header after the handler has run. Deterministic counts replace real clocks.

Go Stand-in: a counting limiter and a post-handler step

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Real rate limiting needs expiry (a token bucket or sliding window, ideally in Redis for several servers). The point here is the shape: count, compare, abort.

Testing middleware

Middleware is easy to test because you can mount it on a tiny engine with a dummy handler and use httptest:

Go
func TestAPIKey(t *testing.T) {
	gin.SetMode(gin.TestMode)
	r := gin.New()
	r.Use(APIKey(map[string]string{"k": "app"}))
	r.GET("/ping", func(c *gin.Context) { c.String(200, "pong") })

	w := httptest.NewRecorder()
	req := httptest.NewRequest("GET", "/ping", nil)
	r.ServeHTTP(w, req)
	if w.Code != 401 {
		t.Fatalf("got %d", w.Code)
	}
}

The testing chapter returns to this approach.

Pitfalls

  • Writing the body, then continuing. If you write a response in a middleware, you must Abort, or the handler writes again.
  • Shared mutable state without locks. One middleware instance serves all requests concurrently. Protect maps and counters with a mutex or atomics.
  • Capturing the context in goroutines. Use c.Copy() for background work started from a middleware or handler.
  • Doing too much. Middleware that loads a database row on every route slows static and health endpoints; attach it to the group that needs it.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why do custom Gin middleware usually come as a constructor returning gin.HandlerFunc?

    The outer function runs once (compile regexes, build maps), the inner closure runs for each request.
  2. 2. A middleware writes a 401 response but forgets c.Abort()/return. What happens?

    Without abort the chain continues; use AbortWithStatusJSON and return.
  3. 3. Which method gives the route pattern (such as /books/:id) for log grouping?

    FullPath returns the registered pattern, not the concrete URL.
  4. 4. How do you safely use the context in a goroutine started inside a handler?

    The original context is reused after the request finishes; Copy gives a safe read-only snapshot.

Summary

  • Write middleware as func Name(cfg) gin.HandlerFunc { return func(c *gin.Context) { ... } }.
  • Do one-time setup in the outer function; per-request work in the closure.
  • Share values with c.Set/c.Get; stop with AbortWithStatusJSON plus return.
  • Guard shared state with locks and use c.Copy() for goroutines.
  • Test middleware with a tiny engine and httptest.

Next: Middleware: Errors and Timeouts centralizes error responses and limits request time.