Home >Backend Development >Golang >Which function in Fiber makes the logic similar to func (c *Context) Set(key string, value any) in gin ?

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

WBOY
WBOYforward
2024-02-06 09:25:04772browse

Fiber 中的哪个函数使逻辑类似于 gin 中的 func (c *Context) Set(key string, value any) ?

Question content

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

I'm looking for a function that writes key/value pairs in a specific context but I didn't find it, please tell me if there is such a chance


Correct answer


Looks like (*ctx).locals is what you want.

The following content is copied from the official document:

locals

A way to store variables that are scoped to the request, so they are only available to routes that match the request.

sign

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

The above is the detailed content of Which function in Fiber makes the logic similar to func (c *Context) Set(key string, value any) in gin ?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete