Gin foundations · 5 MIN READ
Gin route groups: prefixes and middleware are copied at registration, so test the route table
Organize a Gin API into nested, versioned groups with scoped middleware and prove with r.Routes() that every route has the protection you intended.
r.Group("/api/v1") looks like a folder that routes live in, with middleware guarding the door. It is really a registration helper: when you add a route, Gin copies the group's prefix and handler list into that route, and the group plays no part when requests arrive. That one fact explains the most common group bug and tells you how to test for it.
gin · A MAP OF THE IDEA
- Pass middleware to Group
- Register routes after
- List with r.Routes()
- Probe every route
Useful when
- Prefixes and shared middleware are declared once per API area.
- Versions can coexist and be retired independently by prefix.
Watch out
- A late group.Use silently skips earlier routes and subgroups.
- Group middleware never runs for 404, 405 or trailing-slash redirects.
Implementation & operation cost: One table test over r.Routes() and the discipline to pass middleware to Group; nothing at request time beyond the copied chain.
A group is a prefix plus a copied handler list
A RouterGroup holds a base path and a slice of handlers. Group(path, middleware...) returns a new group whose handlers are a fresh copy of the parent's plus the ones you pass. Registering GET or POST on a group joins the paths and copies the group's handlers in front of your handler, and the resulting chain is stored with the route in the router tree. At request time Gin finds the route and runs that stored chain; it never asks which group the route came from. Nesting therefore composes cleanly: /api/v1/admin inherits everything /api/v1 had at the moment the admin group was created, plus its own middleware.
Two versions, an admin subgroup and a route-table test
The program builds a public health check, a v1 group with authentication, an admin subgroup that also requires a role, and a v2 group that changes the response shape. main then lists every route with r.Routes(), calls each one without credentials and labels it, before exercising the authenticated paths.
package main
import (
"fmt"
"net/http"
"net/http/httptest"
"sort"
"strings"
"github.com/gin-gonic/gin"
)
type user struct {
ID int
First string
Last string
}
var users = []user{{ID: 1, First: "Test", Last: "User"}}
// requireToken stands in for real authentication: it maps a bearer token to a role.
func requireToken(c *gin.Context) {
roles := map[string]string{"Bearer user-token": "user", "Bearer admin-token": "admin"}
role, ok := roles[c.GetHeader("Authorization")]
if !ok {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "unauthenticated"})
return
}
c.Set("role", role)
}
func requireRole(want string) gin.HandlerFunc {
return func(c *gin.Context) {
if c.GetString("role") != want {
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": "forbidden"})
return
}
}
}
func health(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"status": "ok"}) }
func listUsersV1(c *gin.Context) {
out := []gin.H{}
for _, u := range users {
out = append(out, gin.H{"id": u.ID, "name": u.First + " " + u.Last})
}
c.JSON(http.StatusOK, out)
}
func listUsersV2(c *gin.Context) {
out := []gin.H{}
for _, u := range users {
out = append(out, gin.H{"id": u.ID, "first_name": u.First, "last_name": u.Last})
}
c.JSON(http.StatusOK, gin.H{"data": out, "next_cursor": nil})
}
func getUserV1(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"id": c.Param("id")}) }
func adminStats(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"users": len(users)}) }
func newRouter() *gin.Engine {
r := gin.New()
r.GET("/health", health)
api := r.Group("/api")
v1 := api.Group("/v1", requireToken)
v1.GET("/users", listUsersV1)
v1.GET("/users/:id", getUserV1)
admin := v1.Group("/admin", requireRole("admin"))
admin.GET("/stats", adminStats)
v2 := api.Group("/v2", requireToken)
v2.GET("/users", listUsersV2)
return r
}
func call(r *gin.Engine, method, path, token string) *httptest.ResponseRecorder {
req := httptest.NewRequest(method, path, nil)
if token != "" {
req.Header.Set("Authorization", "Bearer "+token)
}
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
return w
}
func main() {
gin.SetMode(gin.TestMode)
r := newRouter()
routes := r.Routes()
sort.Slice(routes, func(i, j int) bool { return routes[i].Path < routes[j].Path })
public := map[string]bool{"/health": true}
for _, rt := range routes {
path := strings.ReplaceAll(rt.Path, ":id", "1")
code := call(r, rt.Method, path, "").Code
verdict := "protected"
if code != http.StatusUnauthorized {
verdict = "open"
if !public[rt.Path] {
verdict = "OPEN BY MISTAKE"
}
}
fmt.Println(rt.Method, rt.Path, rt.Handler, code, verdict)
}
fmt.Println("v1", call(r, http.MethodGet, "/api/v1/users", "user-token").Body.String())
fmt.Println("v2", call(r, http.MethodGet, "/api/v2/users", "user-token").Body.String())
fmt.Println("admin as user", call(r, http.MethodGet, "/api/v1/admin/stats", "user-token").Code)
fmt.Println("admin as admin", call(r, http.MethodGet, "/api/v1/admin/stats", "admin-token").Body.String())
}Middleware is passed to Group itself, so it is in place before any route is added. requireToken stores the role with c.Set; requireRole reads it, so the admin chain is requireToken, requireRole("admin"), adminStats in that order. r.Routes() returns method, path and the name of the final handler; the order is not documented, so the program sorts it. Each route is called with its :id replaced by 1 and no Authorization header. Anything that does not answer 401 must be on the public allowlist, or it prints OPEN BY MISTAKE. v1 and v2 share the users slice but render different JSON, and the user token gets 403 from the admin subgroup while the admin token succeeds.
Use after registration protects nothing that came before
group.Use appends to that group's slice. Routes registered earlier already hold their own copy of the chain, and subgroups created earlier hold theirs, so neither gains the new middleware. The failure is silent: the code reads as if the whole /v1 tree is authenticated, the server starts, and the earlier routes answer anyone. Passing middleware as arguments to Group, as the program does, makes the order impossible to get wrong. If you must call Use, call it on the line right after creating the group and before any route or subgroup.
api := r.Group("/api")
v1 := api.Group("/v1")
v1.GET("/export", exportAll) // chain copied now: no auth
admin := v1.Group("/admin") // chain copied now: no auth
v1.Use(requireToken) // appends to v1's own slice only
v1.GET("/users", listUsersV1) // protected
admin.GET("/stats", adminStats) // NOT protectedThis fragment shows the bug, not a pattern to copy. /api/v1/export and /api/v1/admin/stats were wired from v1's chain before requireToken was appended, so both serve unauthenticated requests; only /api/v1/users is protected. The route-table test from the program would print OPEN BY MISTAKE for both, which is why that test exists.
Versions side by side, one core underneath
A v2 group is the place for breaking changes to the HTTP contract: renamed fields, a pagination envelope, stricter validation. Keep both versions as thin adapters over the same application service so a bug fix lands once, and let each group own only its request parsing and response shape. Retire v1 deliberately: label metrics by c.FullPath() so you can see which v1 routes still get traffic, announce the end date with a Sunset response header (RFC 8594) set by a middleware on the v1 group, and delete the group only when its traffic is gone. Versioning by path prefix is the simplest scheme to route, cache and log; header-based versioning is possible but every proxy, cache key and log query then has to know about the header.
What a group cannot see, and what to test
Group middleware runs only for routes registered through that group. A request for /api/v1/typo matches no route, so Gin answers with its 404 chain, which contains only engine-level middleware from r.Use; the same is true for 405 responses, and trailing-slash redirects run no middleware at all. An unauthenticated client therefore gets 404 for unknown paths and 401 for real ones, which is normal but worth knowing when you reason about route enumeration. r.Routes() reports only the last handler of each chain, so you cannot inspect middleware statically; test behavior instead, as the program does. Give handlers names: a named function shows as main.listUsersV1, while an anonymous one appears as something like main.main.func3, which makes a route-table diff useless in review. Run the route-table test in CI so a newly added route without the expected protection fails the build.
TAKE THIS WITH YOU
Pass middleware to Group before registering routes, keep versions as thin adapters over one core, and assert the protection of every entry in r.Routes() with requests rather than trusting how the code reads.
Check your understanding
A team calls v1.Use(auth) after registering some v1 routes and creating v1.Group("/admin"). Which routes does auth protect?
Go to the source
Progress stays in this browser. No account needed.