gofiber / fiber

⚡️ Express inspired web framework written in Go
https://gofiber.io
MIT License
34.04k stars 1.67k forks source link

Add context.Context Support to Additional Middlewares #3212

Open coderabbitai[bot] opened 1 day ago

coderabbitai[bot] commented 1 day ago

Based on the discussion in Issue #3175, we need to extend context support to other middlewares for consistency.

Middlewares to update:

This will ensure that relevant context can be passed through the context.Context in these middlewares.

Requester: @ReneWerner87

ReneWerner87 commented 1 day ago

code from the request id middleware adjustement https://github.com/gofiber/fiber/pull/3200/files

JIeJaitt commented 1 day ago

@ReneWerner87 We need to carefully discuss which middleware need to add requestID, because from the routing to the control layer to the service layer in this process, I see that most of the Go developers will choose to control layer Fiber's Ctx into UserContext, because Fiber as a web framework its function in the whole architecture in the control layer has ended, the service layer will be conducted specific business processing, in the service layer business more concurrent security context, and fiber context is not concurrent security, and requestId in the microservice link tracking is very important to locate the problem, so here will be proposed to increase the request mw UserContext requestID.

The following is the GPT's answer for reference. Fiber's context (ctx) is not inherently thread-safe. Each context instance is tied to a specific request and should only be used within that request's handler goroutine. If you need to access ctx data from different goroutines, you should.

  1. Pass specific data you need instead of the entire ctx
  2. Use proper synchronization mechanisms (mutexes, channels) if sharing data
  3. Clone required data from ctx before passing to goroutines

Example of what to avoid.

app.Get(“/”, func(c *fiber.Ctx) error {
    go func() {
        // UNSAFE: accessing ctx from different goroutine
        data := c.Query(“someData”)
    }()
    return nil
})

Safe approach.

app.Get(“/”, func(c *fiber.Ctx) error {
    data := c.Query(“someData”) // Get data first
    go func(safeData string) {
        // SAFE: using copied data
        process(safeData)
    }(data)
    return nil
})
gaby commented 1 day ago

@JIeJaitt This is for using context.Context, not fasthttp.RequestCtx.