英文:
What function in fiber makes logic similar to func (c *Context) Set(key string, value any) in gin?
问题
在Fiber中,与gin的func (c *Context) Set(key string, value any)
类似的逻辑功能是通过c.Locals(key string, value interface{})
函数实现的。该函数用于在特定的上下文中写入键值对。你可以使用c.Locals(key, value)
来实现你所需的功能。
英文:
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
答案1
得分: 0
看起来(*Ctx).Locals
是你想要的。
以下内容是从官方文档中复制的:
Locals
这是一个将变量存储在请求范围内的方法,因此只能在与请求匹配的路由中使用。
签名
func (c *Ctx) Locals(key interface{}, value ...interface{}) interface{}
示例
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)
})
英文:
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)
})
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论