In go-fiber docs they say:
As a rule of thumb, you must only use context values within the handler, and you must not keep any references
is it OK if I passing around the context as a function argument like this:
func GetList(c *fiber.Ctx) error {
result, err := User.Search(c)
}
func Search(c *fiber.Ctx) (User, err) {
id := c.Params("id")
}
is that considered as a bad practice?
And I don't really understand this sentence:
As soon as you return from the handler, any values you have obtained from the context will be re-used in future requests and will change below your feet.
So if I have sent the response to the client the value of params will be reused? reused by whom? by me or by other people's request?
func GetList(c *fiber.Ctx) error {
id := c.Params("id") // 911
return c.SendString("Hello, World!")
}
so if the value of id was 911 does that mean other people request will also result in 911?
and what's the meaning of
will change below your feet
can anyone elaborate more easy for beginner like me to understand? thanks...
CodePudding user response:
The actual context object can be reused by the framework after it calls your handler, so you cannot rely on its state after you return from the handler.
is it OK if I passing around the context as a function argument like this?
This is fine, as long as Search
doesn't store the context elsewhere. If it just uses values from the context to conduct a search and then returns a result, that's fine.
So if I have sent the response to the client the value of params will be reused? reused by whom? by me or by other people's request?
The actual context object will be reused by the framework, while handling a later request.
and what's the meaning of "will change below your feet"?
If you don't follow the advice above, and instead keep references to the context after returning from your handler, the values in that context will change unexpectedly, since the framework is using that context for a new request.