Routing guide Go Fiber Chinese document 2.x

🔌 Routing

Routing refers to how to respond to requests to clients through application endpoints (URIs).

route

The path contains the request method and the endpoints that can be requested. The path can be a string or a character matching pattern.

Character based routing instance

// The following path will match the request with the route, "/":
app.Get("/", func(c *fiber.Ctx) error {
      return c.SendString("root")
})

// The following path will match the request routed by "/ about":
app.Get("/about", func(c *fiber.Ctx) error {
    return c.SendString("about")
})

// The following path will match the request routed by "/ random.txt":
app.Get("/random.txt", func(c *fiber.Ctx) error {
    return c.SendString("random.txt")
})

parameter

Routing parameters are dynamic elements in routing, which are divided into named parameters and unnamed parameters. The parameter segment is used to capture the value of a specific location in the URL. have access to Params Function, with the routing parameter name specified in the path as the key or with the characters (*, +) for unnamed parameters.

Characters:, +, and * are specially introduced parameter characters

Parameters are represented by a wildcard asterisk (*) or a plus sign (+).

Routing also provides the ability of optional parameters. For named parameters, mark "? At the end Just. Unlike the plus sign, the plus sign is required. You can use wildcards for range parameters. The range is optional and greedy.

Routing instance with routing parameters

// parameter
app.Get("/user/:name/books/:title", func(c *fiber.Ctx) error {
    fmt.Fprintf(c, "%s\n", c.Params("name"))
    fmt.Fprintf(c, "%s\n", c.Params("title"))
    return nil
})
// Plus sign - greedy - required
app.Get("/user/+", func(c *fiber.Ctx) error {
    return c.SendString(c.Params("+"))
})

// Optional parameters
app.Get("/user/:name?", func(c *fiber.Ctx) error {
    return c.SendString(c.Params("name"))
})

// Wildcard - greedy - Optional
app.Get("/user/*", func(c *fiber.Ctx) error {
    return c.SendString(c.Params("*"))
})

// The following route will match the "/ v1/some/resource/name:customVerb" request because the parameter symbol was escaped
app.Get("/v1/some/resource/name\\:customVerb", func(c *fiber.Ctx) error {
    return c.SendString("Hello, Community")
})

Tip: due to hyphen (-) and dot (.) They are interpreted literally, so they can be used together with routing parameters to achieve the purpose.

Tip: all special characters will be escaped by "\ \" and lose their special meaning, so you can use these characters according to your needs in routing, such as implementing these custom methods Google api design guidelines.

// http://localhost:3000/plantae/prunus.persica
app.Get("/plantae/:genus.:species", func(c *fiber.Ctx) error {
    fmt.Fprintf(c, "%s.%s\n", c.Params("genus"), c.Params("species"))
    return nil // prunus.persica
})
// http://localhost:3000/flights/LAX-SFO
app.Get("/flights/:from-:to", func(c *fiber.Ctx) error {
    fmt.Fprintf(c, "%s-%s\n", c.Params("from"), c.Params("to"))
    return nil // LAX-SFO
})

Our intelligent routing can recognize that introductory parameter characters should be part of the request routing and make correct processing, such as:

// http://localhost:3000/shop/product/color:blue/size:xs
app.Get("/shop/product/color::color/size::size", func(c *fiber.Ctx) error {
    fmt.Fprintf(c, "%s:%s\n", c.Params("color"), c.Params("size"))
    return nil // blue:xs
})

In addition, you can use multiple unnamed parameters in the routing line, such as wildcards or plus signs, which will greatly expand the routing diversity of users.

// GET /@v1
// Params: "sign" -> "@", "param" -> "v1"
app.Get("/:sign:param", handler)

// GET /api-v1
// Params: "name" -> "v1" 
app.Get("/api-:name", handler)

// GET /customer/v1/cart/proxy
// Params: "*1" -> "customer/", "*2" -> "/cart"
app.Get("/*v1*/proxy", handler)

// GET /v1/brand/4/shop/blue/xs
// Params: "*1" -> "brand/4", "*2" -> "blue/xs"
app.Get("/v1/*/shop/*", handler)

We have made large-scale routing adjustments, but we will not support regular matching at present because it is too slow. This feature can be tested on version 0.1.7 (express 4), online address Express routing test.

middleware

Middleware functions are designed to make changes to requests or responses. Next It is the routing function of Fiber. Once called, it will execute the next function matching the current route.

Examples of middleware functions

app.Use(func(c *fiber.Ctx) error {
  // Set some security related header information:
  c.Set("X-XSS-Protection", "1; mode=block")
  c.Set("X-Content-Type-Options", "nosniff")
  c.Set("X-Download-Options", "noopen")
  c.Set("Strict-Transport-Security", "max-age=5184000")
  c.Set("X-Frame-Options", "SAMEORIGIN")
  c.Set("X-DNS-Prefetch-Control", "off")

  // Execute the next Middleware
  return c.Next()
})

app.Get("/", func(c *fiber.Ctx) error {
  return c.SendString("Hello, World!")
})

The path of the Use method means mount path or prefix path, and limits the middleware to any request that only starts with this path.

grouping

If the application has many access endpoints, you can use Group to organize routing.

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"))
}

This article was first published in LearnKu.com On the website.

Added by sonofyoda on Sat, 22 Jan 2022 16:16:24 +0200