Question description
I have a function called test which returns multiple values that need to be sent to the browser one by one in separate responses. But I want the function to get executed only once. The body of the post request needs to be passed to the function as an argument so I have to put the function call inside the handler function. I have read about the zero allocation philosophy of fiber and experimented with the immutable setting but I am not sure if that is the problem. Is there any way to achieve what I want?
words, closestScansion, closestMeterKeys, closestMeters, closestMeterNames, problematicWords := [][]string{}, [][]string{}, []string{}, []string{}, []string{}, [][]bool{}
app.Post("/words", func(c *fiber.Ctx) {
if len(words) == 0 {
input = c.Body()
words, closestScansion, closestMeterKeys, closestMeters, closestMeterNames, problematicWords = test(input)
}
wordsJSON := encodeJSON(words)
c.Send(wordsJSON)
})
Thanks for opening your first issue here! 馃帀 Be sure to follow the issue template! If you need help or want to chat with us, join us on Discord https://gofiber.io/discord
Welcome @Chashm-e-Afreen, thank you for opening your first issue!
Taken from https://docs.gofiber.io/#zero-allocation
_values returned from fiber.Ctx are not immutable by default and will be re-used across requests. As a rule of thumb, you must only use context values within the handler, and you must not keep any references. 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._
If you need to persist such values outside the handler, make copies of their underlying buffer using the copy builtin or ImmutableString function provided by gofiber/utils package.
func handler(c *fiber.Ctx) {
mutable := c.Param("foo")
immutable := utils.ImmutableString(c.Param("foo"))
}
Alternatively, you can also use the Immutable setting. It will make all values returned from the context immutable by default, allowing you to persist them anywhere. Of course, this comes at the cost of performance because it would make a copy for each value it returns ( even if you are not planning to use it outside the handler )
app := fiber.New(&fiber.Settings{
Immutable: true,
})
I hope this answers your question!
Thanks a lot for the quick response. But the problem here is that the main function gets called again at each request and the variables are reset. It's my first web development endeavour so I don't know if that's how things are supposed to work or it's just I messing it up somehow.
Turns out that it wasn't actually a problem with fiber. I was using Promise.all with my fetch request which possibly lead to some callback problems. Switched to simple fetch requests with await and it's all fine now.
Awesome 馃憣 I'm closing this issue, feel free to re-open if you have further questions.