問題內容
Fiber 中的哪個函數使邏輯類似于 gin 中的 func (c *Context) Set(key string, value any)?
我正在尋找一個在特定上下文中編寫鍵/值對的函數,但我沒有找到它,請告訴我是否有這樣的機會
正確答案
看起來 (*ctx).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) })
登錄后復制