fiber/docs/guide/grouping.md
M. Efe Çetin b3643198f8
📝 docs: automated synchronization with gofiber/docs (#2344)
Automated Synchronization with gofiber/docs repo
2023-02-25 10:29:07 +01:00

1.7 KiB

id, title, sidebar_position
id title sidebar_position
grouping 🎭 Grouping 2

Paths

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

func main() {
  app := fiber.New()

  api := app.Group("/api", middleware) // /api

  v1 := api.Group("/v1", middleware)   // /api/v1
  v1.Get("/list", handler)             // /api/v1/list
  v1.Get("/user", handler)             // /api/v1/user

  v2 := api.Group("/v2", middleware)   // /api/v2
  v2.Get("/list", handler)             // /api/v2/list
  v2.Get("/user", handler)             // /api/v2/user

  log.Fatal(app.Listen(":3000"))
}

A Group of paths can have an optional handler.

func main() {
  app := fiber.New()

  api := app.Group("/api")      // /api

  v1 := api.Group("/v1")        // /api/v1
  v1.Get("/list", handler)      // /api/v1/list
  v1.Get("/user", handler)      // /api/v1/user

  v2 := api.Group("/v2")        // /api/v2
  v2.Get("/list", handler)      // /api/v2/list
  v2.Get("/user", handler)      // /api/v2/user

  log.Fatal(app.Listen(":3000"))
}

:::caution 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.

func main() {
    app := fiber.New()

    handler := func(c *fiber.Ctx) error {
        return c.SendStatus(fiber.StatusOK)
    }
    api := app.Group("/api") // /api

    v1 := api.Group("/v1", func(c *fiber.Ctx) error { // middleware for /api/v1
        c.Set("Version", "v1")
        return c.Next()
    })
    v1.Get("/list", handler) // /api/v1/list
    v1.Get("/user", handler) // /api/v1/user

    log.Fatal(app.Listen(":3000"))
}