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

huangapple go评论93阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年6月9日 00:42:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/76434044.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定