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 3 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
16 changes: 16 additions & 0 deletions middleware/requestid/requestid.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package requestid

import (
"context"

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

Expand Down Expand Up @@ -36,6 +38,10 @@ 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.UserContext(), requestIDKey, rid)
ReneWerner87 marked this conversation as resolved.
Show resolved Hide resolved
c.SetUserContext(ctx)
gaby marked this conversation as resolved.
Show resolved Hide resolved

// Continue stack
return c.Next()
}
Expand All @@ -49,3 +55,13 @@ func FromContext(c fiber.Ctx) string {
}
return ""
}

// FromUserContext returns the request ID from the UserContext.
// If there is no request ID, an empty string is returned.
// Compared to Local, UserContext is more suitable for transmitting requests between microservices
func FromUserContext(ctx context.Context) string {
gaby marked this conversation as resolved.
Show resolved Hide resolved
if rid, ok := ctx.Value(requestIDKey).(string); ok {
return rid
}
return ""
}
24 changes: 24 additions & 0 deletions middleware/requestid/requestid_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,3 +74,27 @@ func Test_RequestID_FromContext(t *testing.T) {
require.NoError(t, err)
require.Equal(t, reqID, ctxVal)
}

// go test -run Test_RequestID_FromUserContext
func Test_RequestID_FromUserContext(t *testing.T) {
t.Parallel()
reqID := "ThisIsARequestId"

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

var ctxVal string

app.Use(func(c fiber.Ctx) error {
ctxVal = FromUserContext(c.UserContext())
gaby marked this conversation as resolved.
Show resolved Hide resolved
return c.Next()
})

_, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil))
require.NoError(t, err)
require.Equal(t, reqID, ctxVal)
}