DEV Community

Juma
Juma

Posted on

Gin Routing and Middleware

Gin Routing and Middleware: The Bouncers of Your API

Think about the last nightclub you walked past. Before you ever reached the dance floor, a very large person in a black jacket looked you over. Are you on the list? Are you old enough? Are you carrying anything suspicious, like a live chicken? Only after passing the checks did you get in.

Your API needs people like that. Not one giant bouncer who also pours drinks and DJs, but a small crew, each with one job, standing in a line in front of the real action. In Gin, those bouncers are called middleware, and learning to use them well is one of the biggest upgrades you can make to a Go backend.

But first, we need to understand how requests find their way to your code at all. That's routing. Let's start there, and then bring in the bouncers.

Routing: a phone book for URLs

When a request arrives, Gin asks two questions: what method? (GET, POST, PUT, DELETE) and what path? (/users/42). It then looks up the matching function in its routing table and calls it.

The smallest Gin app you can write looks like this:

package main

import (
    "net/http"

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

func main() {
    r := gin.Default()

    r.GET("/ping", func(c *gin.Context) {
        c.JSON(http.StatusOK, gin.H{"message": "pong"})
    })

    r.Run(":8080")
}
Enter fullscreen mode Exit fullscreen mode

Run it, visit /ping, and you get a tiny JSON "pong". That's the whole loop: register a path, attach a function, start the server.

The function that receives *gin.Context is called a handler. The context is your Swiss Army knife for the current request. It carries the incoming data, the tools to read it, and the tools to write the response. Treat it like a clipboard that's handed to every function working on one request, then thrown away when the request ends.

Path parameters and query strings

Real APIs need to say things like "give me user 42." Gin handles this with path parameters, written with a colon:

r.GET("/users/:id", func(c *gin.Context) {
    id := c.Param("id")
    c.JSON(http.StatusOK, gin.H{"requested_user": id})
})
Enter fullscreen mode Exit fullscreen mode

Visit /users/42 and id is the string "42". Note that it's always a string. If you need a number, convert it yourself and handle the failure. People will absolutely send /users/banana.

Query strings, the part after the question mark, are read differently:

// GET /search?q=maize&limit=10
r.GET("/search", func(c *gin.Context) {
    q := c.Query("q")
    limit := c.DefaultQuery("limit", "20")
    c.JSON(http.StatusOK, gin.H{"query": q, "limit": limit})
})
Enter fullscreen mode Exit fullscreen mode

DefaultQuery is a polite way of saying "if they didn't tell me, assume this." Use it for optional things like pagination.

Route groups: stop repeating yourself

Soon your API has dozens of routes, and you'll notice something annoying:

r.GET("/api/v1/products", listProducts)
r.POST("/api/v1/products", createProduct)
r.GET("/api/v1/products/:id", getProduct)
r.GET("/api/v1/orders", listOrders)
Enter fullscreen mode Exit fullscreen mode

Typing /api/v1 over and over is how typos are born. Gin offers groups:

v1 := r.Group("/api/v1")
{
    products := v1.Group("/products")
    {
        products.GET("", listProducts)
        products.POST("", createProduct)
        products.GET("/:id", getProduct)
    }

    orders := v1.Group("/orders")
    {
        orders.GET("", listOrders)
    }
}
Enter fullscreen mode Exit fullscreen mode

The curly braces aren't required. They're a style convention that visually fences each group, like putting related files in a folder. And there's a bonus you'll appreciate in a moment: groups can have middleware attached, so one rule covers a whole section of your API.

Enter the bouncers: what middleware actually is

Here's the definition, stripped of mystery: middleware is a handler that runs before (or after) your real handler.

That's it. A request walks through a corridor, and in that corridor stand several checkpoints. Each checkpoint can:

  1. Look at the request and let it pass.
  2. Modify the request, for instance attaching the logged-in user.
  3. Reject the request and send a response itself, so the real handler never runs.
  4. Do some work after the real handler finishes, such as measuring how long it took.

A middleware has the exact same signature as a handler:

func MyMiddleware() gin.HandlerFunc {
    return func(c *gin.Context) {
        // before the handler
        c.Next()
        // after the handler
    }
}
Enter fullscreen mode Exit fullscreen mode

The function returning a function looks odd at first, but it's useful: the outer function lets you pass in configuration, and the inner one is the actual checkpoint.

The star of the show is c.Next(). It means "pass this request along to the next person in line." Everything you write before c.Next() happens on the way in. Everything after happens on the way out, once the handler has done its work. Picture a sandwich: your middleware is the bread, and the handler is the filling.

Your first middleware: a stopwatch

Let's build something useful and harmless: a timer that logs how long each request takes.

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

        c.Next() // let the real handler run

        duration := time.Since(start)
        log.Printf("%s %s took %v", c.Request.Method, c.Request.URL.Path, duration)
    }
}
Enter fullscreen mode Exit fullscreen mode

Attach it to the whole app:

r := gin.New()
r.Use(Timer())
Enter fullscreen mode Exit fullscreen mode

Now every request prints a line like GET /api/v1/products took 3.2ms. When your API starts feeling slow, these lines are the first place you'll look. Without them you're guessing, and guessing is a terrible debugging strategy.

A real bouncer: authentication middleware

Now the one you came for. Many routes should only be reachable by logged-in users. You could check the token inside every handler, copying the same ten lines everywhere, or you could station one bouncer at the door.

func RequireAuth(tokens TokenVerifier) gin.HandlerFunc {
    return func(c *gin.Context) {
        header := c.GetHeader("Authorization")
        if !strings.HasPrefix(header, "Bearer ") {
            c.AbortWithStatusJSON(http.StatusUnauthorized,
                gin.H{"error": "missing or malformed token"})
            return
        }

        token := strings.TrimPrefix(header, "Bearer ")
        userID, err := tokens.Verify(token)
        if err != nil {
            c.AbortWithStatusJSON(http.StatusUnauthorized,
                gin.H{"error": "invalid or expired token"})
            return
        }

        c.Set("userID", userID)
        c.Next()
    }
}
Enter fullscreen mode Exit fullscreen mode

Three things are worth noticing.

AbortWithStatusJSON stops the line. This is the bouncer saying "you're not coming in." It writes a response and prevents any later middleware or handler from running. Forgetting to abort is a classic bug: you send a 401, but the handler runs anyway and does its work. The client sees an error while your database quietly changes. Not great.

return after aborting. Abort doesn't stop this function from continuing. It only stops the chain. Add return, or your code keeps running past the point where you rejected the request.

c.Set hands information forward. After verifying the token, we attach the user's ID to the context. The handler downstream can pick it up:

func (h *ProfileHandler) Me(c *gin.Context) {
    userID := c.GetUint("userID")
    // use userID to load the profile
}
Enter fullscreen mode Exit fullscreen mode

This is the whole trick. The bouncer checks the wristband, then writes the guest's name on the clipboard for the bartender.

(We'll dig into how to build the TokenVerifier and what makes a JWT safe in a later article. For now, just see the shape.)

Attaching middleware at the right level

Middleware can live at three levels, and choosing correctly is half the skill.

Globally, for every route:

r.Use(gin.Recovery(), Timer())
Enter fullscreen mode Exit fullscreen mode

Good for things that apply to everyone: logging, panic recovery, request IDs.

On a group, for a whole section:

api := r.Group("/api/v1")

public := api.Group("")
public.POST("/login", login)
public.POST("/register", register)

private := api.Group("")
private.Use(RequireAuth(verifier))
private.GET("/me", me)
private.GET("/orders", listOrders)
Enter fullscreen mode Exit fullscreen mode

This is the pattern you'll use constantly. Public routes on one group, protected routes on another, and the auth bouncer posted only at the second door. Add a new protected route, drop it into private, and it's secured automatically. You can't forget, because the safety is built into where you put it.

On a single route, for special cases:

admin.DELETE("/users/:id", RequireRole("admin"), deleteUser)
Enter fullscreen mode Exit fullscreen mode

Extra checks for dangerous actions. Think of it as a second bouncer outside the VIP room.

Order matters (the line has a sequence)

Middleware runs in the order you register it. This sounds obvious, then bites people regularly.

r.Use(gin.Recovery())
r.Use(RequestID())
r.Use(Logger())
r.Use(CORS())
Enter fullscreen mode Exit fullscreen mode

Why this order? Recovery goes first so that a panic in any later piece gets caught instead of crashing your server. RequestID comes before Logger so the logger can print the ID it generated. Reverse them and your logs would be missing exactly the thing that makes them searchable.

A helpful mental image: it's a stack of layers around the handler, like an onion. Requests travel inward through layer one, then layer two, and so on, reach the handler at the core, then travel back out in reverse order. That's why code after c.Next() runs "backwards": last in, first out.

Recovery: the paramedic

Go programs can panic. A nil pointer, an out-of-range index, one forgotten check, and the goroutine dies. Without protection, a single bad request could take down your whole server.

gin.Recovery() is the paramedic standing by. It catches the panic, logs the stack trace, returns a 500 to the client, and keeps the server alive for everyone else. gin.Default() includes it automatically, along with a logger. If you build with gin.New(), as many people do for control, you must add it yourself. A server without recovery is a trapeze act without the net.

CORS: the bouncer who confuses everyone

If you build a vanilla JavaScript frontend on one origin and a Go API on another, say localhost:3000 talking to localhost:8080, your browser will refuse the requests with an angry red console message about CORS. This is not a bug in your code. It's the browser protecting users, and it needs your API to say, explicitly, "yes, that website is allowed to talk to me."

You do this with middleware that sets response headers:

func CORS(allowedOrigin string) gin.HandlerFunc {
    return func(c *gin.Context) {
        c.Header("Access-Control-Allow-Origin", allowedOrigin)
        c.Header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
        c.Header("Access-Control-Allow-Headers", "Authorization, Content-Type")

        if c.Request.Method == http.MethodOptions {
            c.AbortWithStatus(http.StatusNoContent)
            return
        }
        c.Next()
    }
}
Enter fullscreen mode Exit fullscreen mode

The OPTIONS check matters. Before sending certain requests, browsers send a "preflight", a polite knock asking "am I allowed to do this?" Your middleware should answer that knock quickly and end the conversation without running real handlers.

One strong warning: don't set the allowed origin to * on an API that uses cookies or sensitive data just because it makes the error go away. That's the equivalent of firing your bouncer because he was getting in the way. Name the exact origin you trust. There are also well-maintained community packages for CORS if you'd rather not hand-roll it, which is a perfectly sensible choice.

Keeping middleware clean in your architecture

Remember the three layers from the previous article? Middleware belongs in the HTTP layer, alongside handlers. A common home is internal/middleware/, and it should follow the same rule as handlers: translate HTTP things into plain values, and let services handle meaning.

Notice that RequireAuth above takes a TokenVerifier, an interface, rather than reaching for a global secret or touching the database directly. That's the same dependency-injection habit, and it means you can test the middleware with a fake verifier and never need real tokens.

Common mistakes in routing and middleware

Forgetting Abort. Using c.JSON(401, ...) alone doesn't stop the chain. Use AbortWithStatusJSON and return.

Heavy work in global middleware. A database call inside a middleware that runs on every request, including your health check, will quietly drag everything down. Keep global middleware light.

Stuffing business logic into middleware. "If the user's subscription expired, reject." That's a business rule, so it belongs in a service. Middleware should be about the request, not about your product's rules.

Using c.Get without checking. c.Get("userID") returns a value and a boolean saying whether it existed. If you assume it's always there and a route was accidentally placed outside the protected group, you'll get a nil or zero value, and a bug that looks like "everyone is user 0."

Registering routes in a giant main.go. Keep a routes.go or a RegisterRoutes(r *gin.Engine, h Handlers) function, so main stays a recipe and not a novel.

Quick recap

  • Routing matches a method and a path to a handler. Use :id for path parameters and c.Query for query strings.
  • Groups remove repetition and let you attach rules to a whole section.
  • Middleware is a handler that wraps other handlers, with c.Next() as the "pass it along" signal.
  • AbortWithStatusJSON plus return is how a bouncer turns someone away.
  • c.Set and c.Get pass information from middleware to handlers.
  • Order matters: put Recovery first, and anything depending on another middleware's output after it.
  • Attach auth to a group so new routes are protected by default.

Top comments (0)