Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 39 ยท Middleware

Middleware Basics in Gin

Understand how Gin middleware works, from the handler chain, c.Next and c.Abort, global versus group versus route middleware, execution order and a runnable chain stand-in that mirrors Gin's context.

Some code must run for many requests: log the request, check a login token, add a security header, measure how long a handler took. Copying that code into every handler would be tedious and error prone. Middleware is the answer. It is a function with the same signature as a handler (func(c *gin.Context)) that sits in front of your handlers and can run code before and after them, or stop the request entirely.

This chapter starts here. The next lessons cover the built-in Logger and Recovery, writing your own middleware and error handling and timeouts. You have already met the idea in Route Groups, where middleware was attached to a group.

Gin is not available on this site, so the Gin code is read-only. The stand-ins re-create Gin's handler chain (Next, Abort, the index counter) in a few lines of Go that you can run and modify.

Handlers form a chain

A route in Gin is really a list of handlers. When a request matches GET /books, Gin builds the list [Logger, Recovery, authRequired, listBooks] (global middleware first, then group middleware, then the route's own handlers) and calls the first one. Each handler decides whether the chain continues.

Go
func Timing() gin.HandlerFunc {
	return func(c *gin.Context) {
		start := time.Now()

		c.Next() // run everything after this middleware

		log.Printf("%s %s took %s", c.Request.Method, c.Request.URL.Path, time.Since(start))
	}
}

Code before c.Next() runs on the way in; code after it runs on the way out, once the rest of the chain has finished. This "onion" shape is what makes middleware so useful: a single function can measure time, because it sees both ends of the request.

If a middleware never calls c.Next(), Gin calls the following handlers for you when the middleware returns, so a middleware that only inspects the request does not need to call Next explicitly. Call it when you need to run code after the handlers.

Attaching middleware

There are three levels, from broadest to narrowest:

Go
r := gin.New()
r.Use(Timing())                       // 1. global: every route

api := r.Group("/api", authRequired()) // 2. group: every route in the group
api.GET("/books", listBooks)

r.GET("/export", rateLimit(), export)  // 3. route: only this one

Two things to remember:

  • gin.Default() is gin.New() plus the Logger and Recovery middleware. Use gin.New() when you want full control (see Logger and Recovery).
  • Use affects only routes registered after it. This is the same rule as for groups, and the cause of many "why is my route not protected?" mysteries.

Stopping the chain: Abort

A middleware can end the request early. Typical case, authentication:

Go
func authRequired() gin.HandlerFunc {
	return func(c *gin.Context) {
		if c.GetHeader("Authorization") == "" {
			c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "missing token"})
			return
		}
		c.Next()
	}
}

c.Abort() marks the context as finished: handlers further down the chain are skipped. It does not return from your function, which is why a return follows it. AbortWithStatus, AbortWithStatusJSON and AbortWithError combine aborting with a response. Code that is already running keeps running; abort only prevents the next handlers from starting. Middleware that ran before the aborting one still gets to finish its "after Next" part, so the Logger still logs a 401.

c.IsAborted() tells you whether the chain was stopped.

Passing data down the chain

Middleware often computes something the handler needs, such as the current user. The context carries a per-request key/value store:

Go
func loadUser() gin.HandlerFunc {
	return func(c *gin.Context) {
		c.Set("userID", 42)   // set by middleware
		c.Next()
	}
}

func profile(c *gin.Context) {
	id := c.GetInt("userID") // read by handler
	c.JSON(http.StatusOK, gin.H{"id": id})
}

c.Get returns (value, ok), c.MustGet panics when the key is missing, and typed helpers (GetString, GetInt, GetBool...) return zero values. Use constants for keys instead of string literals scattered through the code, so a typo becomes a compile error.

Execution order

Take this setup:

Go
r.Use(A())
api := r.Group("/api", B())
api.GET("/x", C(), handler)

The order is A before > B before > C before > handler > C after > B after > A after. Reading a middleware top to bottom therefore tells you only half the story; the "after" half runs in reverse order.

sequenceDiagram
    participant Client
    participant A as Middleware A
    participant B as Middleware B
    participant H as Handler
    Client->>A: request
    A->>B: c.Next()
    B->>H: c.Next()
    H-->>B: return
    B-->>A: return
    A-->>Client: response

Each c.Next() goes one level deeper; returns unwind in reverse.

Stand-in: Gin's chain in 30 lines

Gin's context keeps an index into the handler list. Next increments it and runs the remaining handlers; Abort moves the index past the end. This runnable program reproduces that, then runs three middleware around a handler so you can see the onion order, and a second request that is aborted.

Go Stand-in: Next and Abort

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.

In the first run the "after" lines unwind in reverse (B after before A after). In the second, auth aborts: the handler never runs, but both after lines still do, because A and B called Next and simply get control back.

Stand-in: real net/http middleware

The standard library expresses middleware as a function that wraps a http.Handler. Gin's model differs in syntax but not in spirit. This runnable example adds a timing header and an auth check around a handler, using nothing but net/http:

Go Stand-in: wrapping handlers with net/http

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.

Both requests pass through A and B (they add their headers), but only the one with a token reaches the handler.

Common mistakes

  • Forgetting return after Abort. The function keeps running and may write a second response.
  • Calling c.Next() inside a goroutine or after the handler returned. The context belongs to the request; if you need it in a goroutine, copy it with c.Copy() first.
  • Registering Use after the routes it should protect.
  • Doing heavy work in global middleware. It runs for static files and health checks too.
  • Hiding errors. A middleware that swallows a failure leaves the client with an unexplained 200.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does c.Next() do inside a middleware?

    Next runs the rest of the chain; code after it executes once the downstream handlers are done.
  2. 2. Middleware A, B and the handler run in order A > B > handler. In what order do the code blocks AFTER c.Next() run?

    Returns unwind in reverse, like nested function calls.
  3. 3. What does c.Abort() NOT do?

    Abort only flags the chain; you still need an explicit return in your function.
  4. 4. What is the difference between gin.New() and gin.Default()?

    gin.Default() is gin.New() plus Logger and Recovery.

Summary

  • Middleware has the same signature as a handler and runs before and after the rest of the chain.
  • c.Next() descends the chain; c.Abort...() stops later handlers; follow it with return.
  • Attach middleware globally (r.Use), to a group, or to a single route.
  • Order: before-code runs outer to inner, after-code inner to outer.
  • Share per-request data with c.Set and c.Get.

Next: Logger and Recovery looks at the two middleware Gin ships by default.