gogo-fiber

What function in fiber makes logic similar to func (c *Context) Set(key string, value any) in gin?


What function in fiber makes logic similar to func (c *Context) Set(key string, value any) in gin?

I was looking for a function to write a key / value pair in a certain context, but I did not find it, please tell me if there is such an opportunity


Solution

  • Looks like (*Ctx).Locals is what you want.

    The following content is copied from the official doc:

    Locals

    A method that stores variables scoped to the request and, therefore, are available only to the routes that match the request.

    Signature

    func (c *Ctx) Locals(key interface{}, value ...interface{}) interface{}
    

    Example

    app.Use(func(c *fiber.Ctx) error {
      c.Locals("user", "admin")
      return c.Next()
    })
    
    app.Get("/admin", func(c *fiber.Ctx) error {
      if c.Locals("user") == "admin" {
        return c.Status(fiber.StatusOK).SendString("Welcome, admin!")
      }
      return c.SendStatus(fiber.StatusForbidden)
    })