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

🔥 feat: Add Context Support to RequestID Middleware #3200

Merged
Merged
Show file tree
Hide file tree
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
10 changes: 10 additions & 0 deletions docs/middleware/requestid.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,16 @@ func handler(c fiber.Ctx) error {
}
```

In version v3, Fiber will inject `requestID` into the built-in `Context` of Go.

```go
func handler(c fiber.Ctx) error {
id := requestid.FromContext(c.Context())
log.Printf("Request ID: %s", id)
return c.SendString("Hello, World!")
}
```

## Config

| Property | Type | Description | Default |
Expand Down
25 changes: 22 additions & 3 deletions middleware/requestid/requestid.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
package requestid

import (
"context"

"github.com/gofiber/fiber/v3"
"github.com/gofiber/fiber/v3/log"
)

// The contextKey type is unexported to prevent collisions with context keys defined in
Expand Down Expand Up @@ -36,16 +39,32 @@ func New(config ...Config) fiber.Handler {
// Add the request ID to locals
c.Locals(requestIDKey, rid)

// Add the request ID to UserContext
ctx := context.WithValue(c.Context(), requestIDKey, rid)
c.SetContext(ctx)

// Continue stack
return c.Next()
}
}

// FromContext returns the request ID from context.
// If there is no request ID, an empty string is returned.
func FromContext(c fiber.Ctx) string {
if rid, ok := c.Locals(requestIDKey).(string); ok {
return rid
// Supported context types:
// - fiber.Ctx: Retrieves request ID from Locals
// - context.Context: Retrieves request ID from context values
func FromContext(c any) string {
switch ctx := c.(type) {
case fiber.Ctx:
if rid, ok := ctx.Locals(requestIDKey).(string); ok {
return rid
}
case context.Context:
if rid, ok := ctx.Value(requestIDKey).(string); ok {
return rid
}
default:
log.Errorf("Unsupported context type: %T. Expected fiber.Ctx or context.Context", c)
}
return ""
}
67 changes: 50 additions & 17 deletions middleware/requestid/requestid_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,26 +51,59 @@ func Test_RequestID_Next(t *testing.T) {
require.Equal(t, fiber.StatusNotFound, resp.StatusCode)
}

// go test -run Test_RequestID_Locals
// go test -run Test_RequestID_FromContext
func Test_RequestID_FromContext(t *testing.T) {
t.Parallel()

reqID := "ThisIsARequestId"

app := fiber.New()
app.Use(New(Config{
Generator: func() string {
return reqID
type args struct {
inputFunc func(c fiber.Ctx) any
}

tests := []struct {
args args
name string
}{
{
name: "From fiber.Ctx",
args: args{
inputFunc: func(c fiber.Ctx) any {
return c
},
},
},
}))

var ctxVal string

app.Use(func(c fiber.Ctx) error {
ctxVal = FromContext(c)
return c.Next()
})

_, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil))
require.NoError(t, err)
require.Equal(t, reqID, ctxVal)
{
name: "From context.Context",
args: args{
inputFunc: func(c fiber.Ctx) any {
return c.Context()
},
},
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()

app := fiber.New()
app.Use(New(Config{
Generator: func() string {
return reqID
},
}))

var ctxVal string

app.Use(func(c fiber.Ctx) error {
ctxVal = FromContext(tt.args.inputFunc(c))
return c.Next()
})

_, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil))
require.NoError(t, err)
require.Equal(t, reqID, ctxVal)
})
}
Comment on lines +86 to +108
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Fix potential race condition and add cleanup.

There are several issues in the test execution:

  1. The ctxVal variable is shared between parallel test executions, which could lead to race conditions
  2. The Fiber app should be cleaned up after tests
  3. The response status code should be verified

Here's how to fix these issues:

 for _, tt := range tests {
   t.Run(tt.name, func(t *testing.T) {
     t.Parallel()

     app := fiber.New()
+    t.Cleanup(func() {
+      _ = app.Shutdown()
+    })

     app.Use(New(Config{
       Generator: func() string {
         return reqID
       },
     }))

-    var ctxVal string
+    var (
+      ctxVal string
+      err    error
+    )

     app.Use(func(c fiber.Ctx) error {
-      ctxVal = FromContext(tt.args.inputFunc(c))
+      defer func() {
+        if r := recover(); r != nil && tt.wantErr {
+          err = fiber.ErrInternalServerError
+        }
+      }()
+      ctxVal = FromContext(tt.args.inputFunc(c))
       return c.Next()
     })

-    _, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil))
-    require.NoError(t, err)
-    require.Equal(t, reqID, ctxVal)
+    resp, testErr := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil))
+    if tt.wantErr {
+      require.Error(t, err)
+      return
+    }
+    require.NoError(t, testErr)
+    require.Equal(t, fiber.StatusNotFound, resp.StatusCode)
+    require.Equal(t, tt.expected, ctxVal)
   })
 }

Committable suggestion skipped: line range outside the PR's diff.

}
Loading