Skip to content

Commit 6c9510d

Browse files
authored
docs: Improve ctx.Locals method description and example (#3030)
1 parent 6c3eb80 commit 6c9510d

File tree

1 file changed

+8
-5
lines changed

1 file changed

+8
-5
lines changed

docs/api/ctx.md

+8-5
Original file line numberDiff line numberDiff line change
@@ -900,28 +900,31 @@ app.Get("/", func(c *fiber.Ctx) error {
900900
901901
## Locals
902902
903-
A method that stores variables scoped to the request and, therefore, are available only to the routes that match the request.
903+
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.
904904
905905
:::tip
906-
This is useful if you want to pass some **specific** data to the next middleware.
906+
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.
907907
:::
908908
909909
```go title="Signature"
910910
func (c *Ctx) Locals(key interface{}, value ...interface{}) interface{}
911911
```
912912
913913
```go title="Example"
914+
type keyType struct{}
915+
var userKey keyType
916+
914917
app.Use(func(c *fiber.Ctx) error {
915-
c.Locals("user", "admin")
918+
c.Locals(userKey, "admin") // Stores the string "admin" under a non-exported type key
916919
return c.Next()
917920
})
918921

919922
app.Get("/admin", func(c *fiber.Ctx) error {
920-
if c.Locals("user") == "admin" {
923+
user, ok := c.Locals(userKey).(string) // Retrieves the data stored under the key and performs a type assertion
924+
if ok && user == "admin" {
921925
return c.Status(fiber.StatusOK).SendString("Welcome, admin!")
922926
}
923927
return c.SendStatus(fiber.StatusForbidden)
924-
925928
})
926929
```
927930

0 commit comments

Comments
 (0)