Basic routing

Routing refers to determining how an application responds to a client request to a particular endpoint, which is a URI (or path) and a specific HTTP request method (GET, PUT, POST and so on).

Each route can have multiple handler functions, that are executed when the route is matched.

Route definition takes the following structures:

  1. // Function signature
  2. app.Method(path string, ...func(*fiber.Ctx))
  • app is an instance of Fiber.
  • Method is an HTTP request method, in capitalization: Get, Put, Post, etc.
  • path is a virtual path on the server.
  • func(*fiber.Ctx) is a callback function containing the Context executed when the route is matched.

Simple route

  1. // Respond with "Hello, World!" on root path, "/"
  2. app.Get("/", func(c *fiber.Ctx) {
  3. c.Send("Hello, World!")
  4. })

Parameters

  1. // GET http://localhost:8080/hello%20world
  2.  
  3. app.Get("/:value", func(c *fiber.Ctx) {
  4. c.Send("Get request with value: " + c.Params("value"))
  5. // => Get request with value: hello world
  6. })

Optional parameter

  1. // GET http://localhost:3000/john
  2.  
  3. app.Get("/:name?", func(c *fiber.Ctx) {
  4. if c.Params("name") != "" {
  5. c.Send("Hello " + c.Params("name"))
  6. // => Hello john
  7. } else {
  8. c.Send("Where is john?")
  9. }
  10. })

Wildcards

  1. // GET http://localhost:3000/api/user/john
  2.  
  3. app.Get("/api/*", func(c *fiber.Ctx) {
  4. c.Send("API path: " + c.Params("*"))
  5. // => API path: user/john
  6. })