Skip to content

fix: add FromStdContext to retrieve request ID from context.Context#4068

Open
veeceey wants to merge 1 commit intogofiber:mainfrom
veeceey:fix/issue-4066
Open

fix: add FromStdContext to retrieve request ID from context.Context#4068
veeceey wants to merge 1 commit intogofiber:mainfrom
veeceey:fix/issue-4066

Conversation

@veeceey
Copy link

@veeceey veeceey commented Feb 8, 2026

Summary

  • Add FromStdContext(ctx context.Context) string function to the requestid middleware, allowing retrieval of the request ID from any standard context.Context
  • Store the request ID in the user context (via context.WithValue) in addition to Fiber locals, so it propagates through c.Context() and wrapped contexts
  • Add tests for FromStdContext including empty context and wrapped context scenarios

Fixes #4066

Test plan

  • All existing requestid middleware tests continue to pass
  • New Test_RequestID_FromStdContext verifies retrieval via c.Context()
  • New Test_RequestID_FromStdContext_Empty verifies empty string on plain context.Background()
  • New Test_RequestID_FromStdContext_WrappedContext verifies retrieval still works when the context is further wrapped with context.WithValue
  • Full test suite passes (only pre-existing client/Test_Client_SetProxyURL/error failure unrelated to this change)

Usage example

```go
import "github.com/gofiber/fiber/v3/middleware/requestid"

func service(ctx context.Context) {
rid := requestid.FromStdContext(ctx) // works!
fmt.Println("Request ID:", rid)
}

app.Get("/test", func(c fiber.Ctx) error {
service(c.Context()) // pass standard context.Context
return c.SendStatus(200)
})
```

The requestid middleware only exposed FromContext(fiber.Ctx) which made
it impossible to retrieve the request ID further down the call stack
when only a standard context.Context was available (e.g. via c.Context()
or c.RequestCtx()).

This stores the request ID in the user context via context.WithValue and
adds FromStdContext(context.Context) so service layers that only receive
a context.Context can access the request ID.

Fixes gofiber#4066
@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello @veeceey, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request significantly improves the usability of the request ID middleware by integrating it more deeply with Go's standard context.Context. Previously, the request ID was primarily accessible via Fiber's Locals. Now, by storing the request ID within the context.Context, it can be seamlessly retrieved in any part of an application that receives a standard context, such as service layers, promoting better traceability and simplifying its usage beyond direct Fiber handler access.

Highlights

  • New Functionality: Introduced a new public function, FromStdContext(ctx context.Context) string, allowing the retrieval of the request ID from any standard Go context.Context.
  • Context Propagation: Modified the request ID middleware to store the generated request ID in the user context via context.WithValue, ensuring it propagates through c.Context() and any wrapped contexts, making it accessible in service layers.
  • Enhanced Test Coverage: Added comprehensive unit tests for the new FromStdContext function, covering scenarios such as retrieval from c.Context(), empty contexts, and contexts that have been further wrapped.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Changelog
  • middleware/requestid/requestid.go
    • Added context package import.
    • Modified the New middleware function to store the generated request ID in the fiber.Ctx's underlying context.Context using context.WithValue.
    • Implemented a new public function FromStdContext(ctx context.Context) string to extract the request ID from any standard context.Context.
  • middleware/requestid/requestid_test.go
    • Added context package import.
    • Introduced Test_RequestID_FromStdContext to verify the correct retrieval of the request ID from c.Context().
    • Added Test_RequestID_FromStdContext_Empty to confirm that FromStdContext returns an empty string when no request ID is present in the context.
    • Included Test_RequestID_FromStdContext_WrappedContext to ensure the request ID can still be retrieved even when the context is further wrapped with additional values.
Activity
  • No human activity (comments, reviews, etc.) has been recorded for this pull request yet.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Feb 8, 2026

Walkthrough

The changes add support for retrieving request IDs from standard context.Context by introducing a new FromStdContext function and storing the request ID in the standard context during middleware execution alongside the existing Fiber context storage.

Changes

Cohort / File(s) Summary
Request ID Standard Context Support
middleware/requestid/requestid.go
Added FromStdContext(ctx context.Context) string function to retrieve request IDs from standard context. Middleware now propagates the generated request ID to both Fiber context (Locals) and standard context via context.WithValue and SetContext.
Request ID Context Tests
middleware/requestid/requestid_test.go
Added three test cases: basic retrieval from standard context, empty context handling, and wrapped context scenarios. Verifies FromStdContext correctly extracts request IDs across different context implementations.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Possibly related PRs

Suggested labels

☢️ Bug, v3

Suggested reviewers

  • gaby
  • sixcolors
  • efectn
  • ReneWerner87

Poem

🐰 Through contexts woven, contexts deep,
A request ID's secrets to keep,
No more trapped in Fiber's embrace,
Standard contexts now have their place! 🪲✨

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately and concisely describes the main change: adding FromStdContext function to retrieve request ID from context.Context.
Description check ✅ Passed The description includes summary, fixes reference, test plan, and usage example. However, it does not fill out the template sections for benchmarks, documentation, changelog, or migration guide checklist items.
Linked Issues check ✅ Passed The PR directly addresses issue #4066 by implementing FromStdContext function and storing request ID in standard context via context.WithValue, enabling retrieval from any context.Context without type assertions.
Out of Scope Changes check ✅ Passed All code changes are directly scoped to the requestid middleware implementation and tests, focusing solely on the FromStdContext feature and context storage requirements without unrelated modifications.
Docstring Coverage ✅ Passed Docstring coverage is 85.71% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

No actionable comments were generated in the recent review. 🎉

🧹 Recent nitpick comments
middleware/requestid/requestid_test.go (1)

260-268: Nit: use a typed key to avoid staticcheck SA1029 warning.

Using a bare string as a context key may trigger a linter warning. A trivial fix:

Suggested change
+	type testKey string
 	app.Use(func(c fiber.Ctx) error {
 		// Wrap the context further (simulating passing through layers)
 		stdCtx := c.Context()
-		wrappedCtx := context.WithValue(stdCtx, "some-other-key", "some-value")
+		wrappedCtx := context.WithValue(stdCtx, testKey("some-other-key"), "some-value")
 
 		// The request ID should still be retrievable from the wrapped context
 		ctxVal = FromStdContext(wrappedCtx)

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@ReneWerner87 ReneWerner87 added this to v3 Feb 8, 2026
@ReneWerner87 ReneWerner87 added this to the v3 milestone Feb 8, 2026
Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request introduces a valuable enhancement to the requestid middleware by adding the FromStdContext function. This allows for retrieving the request ID from a standard context.Context, which is particularly useful for propagating the ID into service layers that are decoupled from Fiber's specific context. The implementation correctly stores the request ID using context.WithValue and is accompanied by thorough tests covering various scenarios, including empty and wrapped contexts. The changes are well-executed and improve the middleware's utility.

Comment on lines +41 to +42
ctx := context.WithValue(c.Context(), requestIDKey, rid)
c.SetContext(ctx)
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

For conciseness, these two lines can be combined into a single call.

Suggested change
ctx := context.WithValue(c.Context(), requestIDKey, rid)
c.SetContext(ctx)
c.SetContext(context.WithValue(c.Context(), requestIDKey, rid))

@gaby
Copy link
Member

gaby commented Feb 8, 2026

@veeceey Please discuss in the issue first, we are still investigation internally.

@veeceey
Copy link
Author

veeceey commented Feb 8, 2026

Thanks @gaby, understood! I'll follow up in #4066 and wait for the team's decision before making further changes here. Happy to adjust the approach based on your internal discussion.

@veeceey
Copy link
Author

veeceey commented Feb 9, 2026

Understood @gaby, will hold off and wait for the team's direction. I've also commented on #4066. Happy to revise the approach once you've settled on the preferred solution.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

Status: No status

Development

Successfully merging this pull request may close these issues.

🐛 [Bug]: No way of accessing requestid value other than from fiber.Ctx

3 participants