🎭 Grouping

Paths

Like Routing, groups can also have paths that belong to a cluster.

  1. func main() {
  2. app := fiber.New()
  3. api := app.Group("/api", middleware) // /api
  4. v1 := api.Group("/v1", middleware) // /api/v1
  5. v1.Get("/list", handler) // /api/v1/list
  6. v1.Get("/user", handler) // /api/v1/user
  7. v2 := api.Group("/v2", middleware) // /api/v2
  8. v2.Get("/list", handler) // /api/v2/list
  9. v2.Get("/user", handler) // /api/v2/user
  10. app.Listen(3000)
  11. }

A Group of paths can have an optional handler.

  1. func main() {
  2. app := fiber.New()
  3. api := app.Group("/api") // /api
  4. v1 := api.Group("/v1") // /api/v1
  5. v1.Get("/list", handler) // /api/v1/list
  6. v1.Get("/user", handler) // /api/v1/user
  7. v2 := api.Group("/v2") // /api/v2
  8. v2.Get("/list", handler) // /api/v2/list
  9. v2.Get("/user", handler) // /api/v2/user
  10. app.Listen(3000)
  11. }
Running /api, /v1 or /v2 will result in 404 error, make sure you have the errors set.

Group Handlers

Group handlers can also be used as a routing path but they must have Next added to them so that the flow can continue.

  1. func main() {
  2. app := fiber.New()
  3. api := app.Group("/api") // /api
  4. v1 := api.Group("/v1", func(c *fiber.Ctx) error {
  5. c.JSON(fiber.Map{
  6. "message": "v1",
  7. })
  8. return c.Next()
  9. }) // /api/v1
  10. v1.Get("/list", handler) // /api/v1/list
  11. v1.Get("/user", handler) // /api/v1/user
  12. app.Listen(3000)
  13. }