description: >- Routing refers to how an application’s endpoints (URIs) respond to client

requests.

🔌 Routing

Paths

Route paths, in combination with a request method, define the endpoints at which requests can be made. Route paths can be strings or string patterns.

Examples of route paths based on strings

  1. // This route path will match requests to the root route, "/":
  2. app.Get("/", func(c *fiber.Ctx) {
  3. c.Send("root")
  4. })
  5. // This route path will match requests to "/about":
  6. app.Get("/about", func(c *fiber.Ctx) {
  7. c.Send("about")
  8. })
  9. // This route path will match requests to "/random.txt":
  10. app.Get("/random.txt", func(c *fiber.Ctx) {
  11. c.Send("random.txt")
  12. })

Parameters

Route parameters are named URL segments that are used to capture the values specified at their position in the URL. The captured values can be retrieved using the Params function, with the name of the route parameter specified in the path as their respective keys.

Name of the route parameter must be made up of characters ([A-Za-z0-9_]).

The hyphen (-) are not interpreted literally yet. Planned for Fiber v1.10.

Example of define routes with route parameters

  1. // Parameters
  2. app.Get("/user/:name/books/:title", func(c *fiber.Ctx) {
  3. c.Write(c.Params("name"))
  4. c.Write(c.Params("title"))
  5. })
  6. // Wildcard
  7. app.Get("/user/*", func(c *fiber.Ctx) {
  8. c.Send(c.Params("*"))
  9. })
  10. // Optional parameter
  11. app.Get("/user/:name?", func(c *fiber.Ctx) {
  12. c.Send(c.Params("name"))
  13. })

Middleware

Functions, that are designed to make changes to the request or response, are called middleware functions. The Next is a Fiber router function, when called, executes the next function that matches the current route.

Example of a middleware function

  1. app.Use(func(c *fiber.Ctx) {
  2. // Set some security headers:
  3. c.Set("X-XSS-Protection", "1; mode=block")
  4. c.Set("X-Content-Type-Options", "nosniff")
  5. c.Set("X-Download-Options", "noopen")
  6. c.Set("Strict-Transport-Security", "max-age=5184000")
  7. c.Set("X-Frame-Options", "SAMEORIGIN")
  8. c.Set("X-DNS-Prefetch-Control", "off")
  9. // Go to next middleware:
  10. c.Next()
  11. })
  12. app.Get("/", func(c *fiber.Ctx) {
  13. c.Send("Hello, World!")
  14. })

Use method path is a mount or prefix path and limits middleware to only apply to any paths requested that begin with it. This means you cannot use :params on the Use method.

Grouping

If you have many endpoints, you can organize your routes using Group

  1. func main() {
  2. app := fiber.New()
  3. api := app.Group("/api", cors()) // /api
  4. v1 := api.Group("/v1", mysql()) // /api/v1
  5. v1.Get("/list", handler) // /api/v1/list
  6. v1.Get("/user", handler) // /api/v1/user
  7. v2 := api.Group("/v2", mongodb()) // /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. }