Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs: Improve ctx.Locals method description and example #3030

Merged
merged 1 commit into from
Jun 11, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 8 additions & 5 deletions docs/api/ctx.md
Original file line number Diff line number Diff line change
Expand Up @@ -900,28 +900,31 @@ app.Get("/", func(c *fiber.Ctx) error {

## Locals

A method that stores variables scoped to the request and, therefore, are available only to the routes that match the request.
A method that stores variables scoped to the request and, therefore, are available only to the routes that match the request. The stored variables are removed after the request is handled. If any of the stored data implements the `io.Closer` interface, its `Close` method will be called before it's removed.

:::tip
This is useful if you want to pass some **specific** data to the next middleware.
This is useful if you want to pass some **specific** data to the next middleware. Remember to perform type assertions when retrieving the data to ensure it is of the expected type. You can also use a non-exported type as a key to avoid collisions.
:::

```go title="Signature"
func (c *Ctx) Locals(key interface{}, value ...interface{}) interface{}
```

```go title="Example"
type keyType struct{}
var userKey keyType

app.Use(func(c *fiber.Ctx) error {
c.Locals("user", "admin")
c.Locals(userKey, "admin") // Stores the string "admin" under a non-exported type key
return c.Next()
})

app.Get("/admin", func(c *fiber.Ctx) error {
if c.Locals("user") == "admin" {
user, ok := c.Locals(userKey).(string) // Retrieves the data stored under the key and performs a type assertion
if ok && user == "admin" {
return c.Status(fiber.StatusOK).SendString("Welcome, admin!")
}
return c.SendStatus(fiber.StatusForbidden)

})
```

Expand Down
Loading