🎭 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. log.Fatal(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. log.Fatal(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. handler := func(c *fiber.Ctx) error {
  4. return c.SendStatus(fiber.StatusOK)
  5. }
  6. api := app.Group("/api") // /api
  7. v1 := api.Group("/v1", func(c *fiber.Ctx) error { // middleware for /api/v1
  8. c.Set("Version", "v1")
  9. return c.Next()
  10. })
  11. v1.Get("/list", handler) // /api/v1/list
  12. v1.Get("/user", handler) // /api/v1/user
  13. log.Fatal(app.Listen(":3000"))
  14. }