Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 39 ยท Routing and Handlers

Route Groups in Gin

Use r.Group in Gin to share a path prefix and middleware, nest groups, version an API, protect admin routes and build a runnable group stand-in that shows how prefixes and middleware combine.

As an API grows you end up repeating yourself: ten routes that all start with /api/v1, six of which need an authentication check. A route group solves both problems. It is an object with a shared path prefix and a shared list of middleware, and every route you add to it inherits both. This lesson builds on Routes and HTTP Methods and prepares you for middleware.

Creating a group

r.Group(prefix) returns a *gin.RouterGroup. You register routes on it with the same methods you use on the engine (GET, POST, and so on):

Go
r := gin.Default()

v1 := r.Group("/api/v1")
{
	v1.GET("/users", listUsers)       // GET /api/v1/users
	v1.GET("/users/:id", getUser)     // GET /api/v1/users/42
	v1.POST("/users", createUser)     // POST /api/v1/users
}

The braces are only a visual convention. They are a plain Go block that shows which routes belong together; Gin does not need them. The engine itself is also a group (the root group with the prefix /), which is why r.GET and v1.GET have the same shape.

Nesting groups

A group can contain groups. The prefixes add up:

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

users := v1.Group("/users")
users.GET("", listUsers)        // /api/v1/users
users.GET("/:id", getUser)      // /api/v1/users/:id

Note that the inner path is "" (empty) for the collection route; it avoids a trailing slash. If both /users and /users/ could be requested, remember Gin redirects between the two forms.

Versioning is the most common use of groups. When version 2 changes a response shape, you keep v1 running unchanged and register new handlers on v2.

Middleware on groups

The second job of a group is to apply middleware to a set of routes. Pass middleware as extra arguments to Group, or call Use on the group:

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

private := r.Group("/api", authRequired())   // middleware as an argument
private.GET("/me", me)
private.GET("/orders", listOrders)

admin := private.Group("/admin")
admin.Use(adminOnly())                        // or with Use
admin.DELETE("/users/:id", deleteUser)

A group inherits the middleware of its parent and may add more. The route DELETE /api/admin/users/:id runs authRequired, then adminOnly, then deleteUser. POST /api/login runs neither check, because it was registered on a different group.

Order matters: middleware added with Use only applies to routes registered after the call. If you call private.Use(auth) and then register private.GET("/me", ...), the route is protected. Register the route first and call Use afterwards, and it is not. Always put Use at the top of the group.

A runnable group stand-in

Gin's groups compute the full path and the combined handler chain at registration time. The stand-in below does the same thing in about 40 lines, so you can watch prefixes and middleware combine. Each middleware appends its name to a trace so you can see the order.

Go Stand-in: groups combine prefixes and 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.

Read the output: the login route runs only logger; the profile route adds auth; the admin route runs logger > auth > adminOnly > stats. Notice the snapshot in GET: the chain is copied when the route is registered, which is exactly why a Use call placed after a route does not affect it.

Groups and project structure

Groups fit the feature-per-file layout from Structuring a Gin Project. Each feature exposes a Register method that receives a group:

Go
func (h *UserHandler) Register(rg *gin.RouterGroup) {
	users := rg.Group("/users")
	users.GET("", h.List)
	users.GET("/:id", h.Get)
	users.POST("", h.Create)
}

func NewRouter(users *UserHandler, orders *OrderHandler) *gin.Engine {
	r := gin.New()
	api := r.Group("/api/v1")
	users.Register(api)
	orders.Register(api)
	return r
}

Adding a feature means writing one file and one extra Register call.

Handy group patterns

Public and protected. Keep authentication routes (/login, /register) on a group without the auth middleware, and everything else on one with it. Writing Custom Middleware shows how to build authRequired.

Per-resource middleware. Load an object once for a set of routes, such as the book that /books/:id/... refers to, and store it with c.Set. Child routes then read it with c.MustGet.

Group-level rate limits. Apply a stricter limit to /api/login than to the rest, by putting login on its own group.

Static and API side by side. Serve a web app from / and the API from /api; the group prefix keeps them from clashing. The templates and static files chapter covers serving a front end.

Checking what you registered

r.Routes() returns every registered route, including groups' full paths. Printing it in debug mode is a quick way to confirm that a prefix combined the way you expected:

Go
for _, ri := range r.Routes() {
	fmt.Printf("%-7s %-28s %s\n", ri.Method, ri.Path, ri.Handler)
}

You will recognize this output from Gin Modes, Configuration and Environment.

A second stand-in: versioned APIs on net/http

The standard library has no groups, but you can build the prefix half yourself with http.StripPrefix and a sub-mux. This is useful when you want to mount a whole sub-application:

Go Stand-in: mounting v1 and v2 on one server

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.

Gin's groups give you the same result with less ceremony, plus middleware inheritance.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the effective path of users.GET("/:id") when users := r.Group("/api").Group("/v1").Group("/users")?

    Group prefixes concatenate: /api + /v1 + /users + /:id.
  2. 2. A route is registered on a group BEFORE group.Use(mw) is called. Does mw run for that route?

    Handler chains are built at registration time, so Use must come first.
  3. 3. Which statement about group middleware is true?

    A group inherits its parent's chain; extra middleware is appended for the child only.
  4. 4. What are the braces after r.Group(...) in the examples?

    They are an ordinary block. Gin does not need them; they just show which routes belong to the group.

Summary

  • r.Group(prefix) shares a path prefix and middleware across related routes.
  • Groups nest; prefixes concatenate and child groups inherit the parent's middleware.
  • Common uses: API versioning, public versus authenticated routes, admin areas.
  • Call Use before registering routes; the chain is captured at registration.
  • Let each feature register its own routes on a *gin.RouterGroup.

Next: Responses: JSON, XML, HTML and More covers everything a handler can send back.