-
-
Notifications
You must be signed in to change notification settings - Fork 1.9k
📒 docs: Add context guide #3677
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
Conversation
|
Note Other AI code review bot(s) detectedCodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review. WalkthroughAdds a new documentation page explaining that Changes
Sequence Diagram(s)sequenceDiagram
participant Client
participant Handler
participant FiberCtx as fiber.Ctx (context.Context)
participant Goroutine as background goroutine
participant FasthttpCtx as fasthttp.RequestCtx
Client->>Handler: HTTP request
Handler->>FiberCtx: receive c (fiber.Ctx)
Handler->>Goroutine: start async work with ctx := context.WithTimeout(FiberCtx, ...)
note right of Goroutine: Goroutine uses ctx for cancellation/deadline
Client->>FasthttpCtx: disconnect
FasthttpCtx-->>FiberCtx: notify via fasthttpctx (Done closes, Err=Canceled)
FiberCtx-->>Goroutine: ctx.Done() triggers cancellation
Estimated code review effort🎯 1 (Trivial) | ⏱️ ~2 minutes Possibly related PRs
Suggested labels
Suggested reviewers
Poem
Tip 🔌 Remote MCP (Model Context Protocol) integration is now available!Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats. ✨ Finishing Touches🧪 Generate unit tests
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. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. CodeRabbit Commands (Invoked using PR/Issue comments)Type Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Summary of Changes
Hello @gaby, 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!
I've added a new documentation guide that clarifies how Fiber's Ctx integrates with Go's standard context.Context interface. This guide explains how developers can leverage this integration for passing request-scoped values and signals, including how to interact with the underlying fasthttp.RequestCtx. It also covers the various helper functions provided by Fiber middleware for easily retrieving common context-bound data.
Highlights
- Fiber
Ctxandcontext.Contextintegration: The new guide explains thatfiber.Ctxnow implements Go'scontext.Contextinterface, allowing direct passing to functions expectingcontext.Context. It also notes the currentfasthttplimitations whereDeadline,Done, andErrmethods are no-ops. fasthttp.RequestCtxandfasthttpctxusage: The documentation details how to access the underlyingfasthttp.RequestCtxviac.RequestCtx()for low-level API access and clarifies howfasthttpctxenablesfasthttpto satisfycontext.Context, despite its own limitations regarding deadlines and cancellation.- Context Helper Functions: The guide covers several middleware-provided helper functions for retrieving request-scoped values, including
requestid.FromContext,csrf.TokenFromContext,session.FromContext,basicauth.UsernameFromContext, andkeyauth.TokenFromContext. - Integrating with
context.WithValueand friends: It demonstrates how standardcontextpackage helpers likecontext.WithValue,context.WithTimeout, andcontext.WithCancelcan be used to wrap the request context, emphasizing consistent API usage and future-proofing despite currentfasthttplimitations.
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 in your pull request via creating an issue comment (i.e. comment on the pull request page) using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands.
| 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 issue 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 or fill out our survey to provide feedback.
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
-
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. ↩
There was a problem hiding this 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 adds a new documentation guide for using context.Context with Fiber. The guide is well-structured and covers the main aspects. However, there are a few areas where the explanation of fasthttp.RequestCtx's behavior and its interaction with fiber.Ctx is inaccurate or unclear. I've provided suggestions to improve the correctness and clarity of these sections, particularly around client disconnects and creating cancellable contexts.
|
/gemini review |
There was a problem hiding this 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 adds a new documentation page explaining how to use Fiber's context, its integration with Go's context.Context, and various context helper functions from middleware. The documentation is well-structured, accurate, and provides useful examples. I have one suggestion to improve the clarity of a code snippet.
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Pull Request Overview
This PR adds comprehensive documentation for Fiber's context system, explaining how Fiber's Ctx integrates with Go's context.Context interface and how to work with request-scoped data. The guide covers the implementation details, limitations, and practical usage patterns for context handling in Fiber applications.
- Documents Fiber's
Ctxas implementingcontext.Contextwith current limitations - Explains accessing the underlying
fasthttp.RequestCtxandfasthttpctxlayer - Provides examples of context helper functions from various middleware packages
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
♻️ Duplicate comments (1)
docs/guide/context.md (1)
102-112: Retitle the snippet to make the scenario explicit.Minor clarity improvement: make it clear this is a logout flow. This also addresses a prior suggestion.
-```go title="Deleting a token" +```go title="Deleting a token on logout"
🧹 Nitpick comments (8)
docs/guide/context.md (8)
12-14: Remove unused imports (Tabs/TabItem).These components aren’t used in this page. Dropping them avoids dead imports and reduces confusion.
-import Tabs from '@theme/Tabs'; -import TabItem from '@theme/TabItem';
17-23: Avoid time-relative “now” and spell out no-op behaviors explicitly.Small clarity tweaks: avoid “now” (docs age better) and explicitly describe Deadline/Done/Err behaviors for
fiber.Ctx.-Fiber's [`Ctx`](../api/ctx.md) now implements Go's +Fiber's [`Ctx`](../api/ctx.md) implements Go's [`context.Context`](https://pkg.go.dev/context#Context) interface. This means you can pass the context directly to functions that expect `context.Context` without any adapters. -However, due to current limitations in `fasthttp`, the -`Deadline`, `Done`, and `Err` methods are implemented as no-ops【F:docs/api/ctx.md†L44-L53】. +However, due to current limitations in `fasthttp`, the `Deadline`, `Done`, and +`Err` methods are effectively no-ops: `Deadline` returns no deadline, +`Done` is `nil`, and `Err` is `nil`.
37-40: Clarify interaction between Locals and context.WithValue.As written, this could imply
c.Valuereads values set via a derived context. In practice,c.Valueis backed byLocals, whilecontext.WithValue(c, ...)returns a derived context whose values are read via that returned context, notc.-`Ctx.Value` is backed by [Locals](../api/ctx.md#locals). Values stored -with `c.Locals` can be read back via the `Value` method or through -`context.WithValue` helpers【F:docs/api/ctx.md†L66-L74】. +`Ctx.Value` is backed by [Locals](../api/ctx.md#locals). Values stored with +`c.Locals` are readable via `c.Value`. If you use `context.WithValue(c, ...)`, +it returns a new derived context; read those values from the returned context, +not from `c` itself.
51-55: Rephrase to attributeDonesemantics tofasthttp.RequestCtxand link precisely.The semantics (no deadline;
Donecloses on client disconnect;Errbecomescontext.Canceled) are properties offasthttp.RequestCtx’scontext.Contextimplementation. Refer to it directly and add a precise link. If a separate “fasthttpctx” layer is intended, please add its import path and link.-The underlying [`fasthttp.RequestCtx`](https://pkg.go.dev/github.com/valyala/fasthttp#RequestCtx) -can be accessed via `c.RequestCtx()`【F:ctx.go†L104-L108】. -This exposes low level APIs and the context support provided by the -`fasthttpctx` layer. +The underlying [`fasthttp.RequestCtx`](https://pkg.go.dev/github.com/valyala/fasthttp#RequestCtx) +can be accessed via `c.RequestCtx()`. This exposes low-level `fasthttp` APIs +and its `context.Context` implementation. -`fasthttpctx` enables `fasthttp` to satisfy the `context.Context` interface. -`Deadline` always reports no deadline, `Done` is closed when the client -connection ends, and once it fires `Err` reports `context.Canceled`. This -means handlers can detect client disconnects while still passing -`c.RequestCtx()` into APIs that expect a `context.Context`. +For `fasthttp.RequestCtx`, `Deadline` always reports no deadline; `Done` closes +when the client connection ends; and once it fires, `Err` reports +`context.Canceled`. This lets handlers detect client disconnects while still +passing `c.RequestCtx()` into APIs that expect a `context.Context`.If “fasthttpctx” is a distinct package you intend to reference, please provide its exact import path and link to the docs to avoid confusion.
Also applies to: 65-70
156-163: Call out required imports for the timeout example.A short note avoids confusion for less experienced users.
Since `fiber.Ctx` conforms to `context.Context`, standard helpers such as `context.WithValue`, `context.WithTimeout`, or `context.WithCancel` can wrap the request context when needed. + +Note: import `"context"` and `"time"` for the following example. ```go app.Get("/job", func(c fiber.Ctx) error {
173-178: Add guidance on when to usec.RequestCtx()vs derived contexts.Make the trade-off explicit: client-disconnect vs server-driven cancellation.
Even though the base `fiber.Ctx` never cancels on its own, wrapping it with helpers like `context.WithTimeout` creates a derived context that honors deadlines and cancellation for any operations you launch from the handler. This common pattern lets you coordinate work with external APIs or databases while keeping a familiar API. +If you need cancellation on client disconnect specifically, prefer passing +`c.RequestCtx()`; if you need server-driven timeouts/cancellation, create a +derived context (e.g., `context.WithTimeout(c, ...)`) and pass that instead.
181-188: Be precise about “no-ops” in the summary.Mirrors the earlier clarification so readers leave with exact semantics.
-- `fiber.Ctx` satisfies `context.Context` but its `Deadline`, `Done`, and `Err` - methods are currently no-ops. +- `fiber.Ctx` satisfies `context.Context`, but: `Deadline` returns no deadline; + `Done` is `nil`; and `Err` is `nil`.
22-22: Remove inline “【F:...】” citation markers or convert them to standard links.These bracketed markers aren’t standard in Docusaurus and will leak tooling artifacts into published docs. Either remove them or replace with proper inline links to the relevant docs pages/anchors.
-... no-ops【F:docs/api/ctx.md†L44-L53】. +... no-ops. -... helpers【F:docs/api/ctx.md†L66-L74】. +... helpers. -... `c.RequestCtx()`【F:ctx.go†L104-L108】. +... `c.RequestCtx()`. -Use `requestid.FromContext` to read it later【F:docs/middleware/requestid.md†L11-L14】【F:docs/middleware/requestid.md†L44-L51】. +Use `requestid.FromContext` to read it later. -... current context【F:docs/middleware/csrf.md†L111-L133】【F:docs/middleware/csrf.md†L452-L475】. +... current context. -`session.FromContext`【F:docs/middleware/session.md†L22-L46】. +`session.FromContext`. -`basicauth.UsernameFromContext`【F:docs/middleware/basicauth.md†L14-L18】. +`basicauth.UsernameFromContext`. -`keyauth.TokenFromContext`【F:docs/middleware/keyauth.md†L9-L14】. +`keyauth.TokenFromContext`.Optionally add proper inline links, e.g.
[requestid.FromContext](../middleware/requestid.md), mirroring the site’s linking style.Also applies to: 39-40, 52-53, 79-80, 92-93, 117-118, 131-132, 144-145
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled by default for public repositories
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (1)
docs/guide/context.md(1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
docs/**
📄 CodeRabbit Inference Engine (.github/copilot-instructions.md)
Review and update the contents of the
docsfolder if necessary when modifying code
Files:
docs/guide/context.md
🧠 Learnings (4)
📓 Common learnings
Learnt from: gaby
PR: gofiber/fiber#3193
File: middleware/cache/cache_test.go:897-897
Timestamp: 2024-11-08T04:10:42.990Z
Learning: In the Fiber framework, `Context()` is being renamed to `RequestCtx()`, and `UserContext()` to `Context()` to improve clarity and align with Go's context conventions.
Learnt from: gaby
PR: gofiber/fiber#3193
File: middleware/adaptor/adaptor.go:111-111
Timestamp: 2024-11-10T23:44:13.704Z
Learning: In the `middleware/adaptor/adaptor.go` file of the Fiber framework, when updating context handling, replacing `c.Context()` with `c.RequestCtx()` is appropriate to access the `fasthttp.RequestCtx`.
📚 Learning: 2024-11-10T23:44:13.704Z
Learnt from: gaby
PR: gofiber/fiber#3193
File: middleware/adaptor/adaptor.go:111-111
Timestamp: 2024-11-10T23:44:13.704Z
Learning: In the `middleware/adaptor/adaptor.go` file of the Fiber framework, when updating context handling, replacing `c.Context()` with `c.RequestCtx()` is appropriate to access the `fasthttp.RequestCtx`.
Applied to files:
docs/guide/context.md
📚 Learning: 2024-11-08T04:10:42.990Z
Learnt from: gaby
PR: gofiber/fiber#3193
File: middleware/cache/cache_test.go:897-897
Timestamp: 2024-11-08T04:10:42.990Z
Learning: In the Fiber framework, `Context()` is being renamed to `RequestCtx()`, and `UserContext()` to `Context()` to improve clarity and align with Go's context conventions.
Applied to files:
docs/guide/context.md
📚 Learning: 2024-11-29T12:37:27.581Z
Learnt from: efectn
PR: gofiber/fiber#3162
File: app_test.go:893-895
Timestamp: 2024-11-29T12:37:27.581Z
Learning: In the `Test_App_ShutdownWithContext` function in `app_test.go`, the `clientDone` channel is used to synchronize the client's request completion before proceeding, eliminating the need for additional `time.Sleep` calls.
Applied to files:
docs/guide/context.md
🪛 LanguageTool
docs/guide/context.md
[grammar] ~12-~12: There might be a mistake here.
Context: ...: 4 --- import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; #...
(QB_NEW_EN)
[grammar] ~20-~20: There might be a mistake here.
Context: ... context.Context without any adapters. However, due to current limitations in `...
(QB_NEW_EN)
[grammar] ~21-~21: There might be a mistake here.
Context: ...o current limitations in fasthttp, the Deadline, Done, and Err methods ar...
(QB_NEW_EN)
[grammar] ~22-~22: Ensure spelling is correct
Context: ...and Err methods are implemented as no-ops【F:docs/api/ctx.md†L44-L53】. ```go title="Exam...
(QB_NEW_EN_ORTHOGRAPHY_ERROR_IDS_1)
[grammar] ~38-~38: There might be a mistake here.
Context: ...d back via the Value method or through context.WithValue helpers【F:docs/api/c...
(QB_NEW_EN)
[grammar] ~39-~39: Ensure spelling is correct
Context: ...method or throughcontext.WithValue` helpers【F:docs/api/ctx.md†L66-L74】. ```go title="Loca...
(QB_NEW_EN_ORTHOGRAPHY_ERROR_IDS_1)
[grammar] ~53-~53: There might be a mistake here.
Context: ... and the context support provided by the fasthttpctx layer. ```go title="Acces...
(QB_NEW_EN)
[grammar] ~66-~66: There might be a mistake here.
Context: ...adline, Done is closed when the client connection ends, and once it fires Err...
(QB_NEW_EN)
[grammar] ~73-~73: There might be a mistake here.
Context: ...expose a number of helper functions that retrieve request-scoped values from the ...
(QB_NEW_EN)
[grammar] ~79-~79: Ensure spelling is correct
Context: ... Use requestid.FromContext to read it later【F:docs/middleware/requestid.md†L11-L14】【F:docs...
(QB_NEW_EN_ORTHOGRAPHY_ERROR_IDS_1)
[grammar] ~91-~91: There might be a mistake here.
Context: ...elpers to fetch the token or the handler attached to the current context【F:docs/m...
(QB_NEW_EN)
[grammar] ~92-~92: Ensure spelling is correct
Context: ... or the handler attached to the current context【F:docs/middleware/csrf.md†L111-L133】【F:docs/mi...
(QB_NEW_EN_ORTHOGRAPHY_ERROR_IDS_1)
[grammar] ~157-~157: There might be a mistake here.
Context: ...xt.WithTimeout, or context.WithCancel` can wrap the request context when needed...
(QB_NEW_EN)
[grammar] ~175-~175: There might be a mistake here.
Context: ...ations you launch from the handler. This common pattern lets you coordinate work ...
(QB_NEW_EN)
[grammar] ~176-~176: There might be a mistake here.
Context: ...rk with external APIs or databases while keeping a familiar API. ## Summary - `...
(QB_NEW_EN)
[grammar] ~184-~184: There might be a mistake here.
Context: ...loses when the client connection ends. - Middleware helpers like `requestid.FromC...
(QB_NEW_EN)
[grammar] ~186-~186: There might be a mistake here.
Context: ...it easy to retrieve request-scoped data. - Standard helpers such as `context.WithTi...
(QB_NEW_EN)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
🧹 Nitpick comments (6)
docs/guide/context.md (6)
12-14: Remove unused imports (Tabs/TabItem).These components aren’t used in this page. Keeping them can confuse readers and cause unnecessary bundling.
-import Tabs from '@theme/Tabs'; -import TabItem from '@theme/TabItem'; +
17-23: Clarify wording and explicitly define “no-op” semantics.
- “now implements” is time-relative and can age poorly.
- Spell out the exact behaviors of the no-op methods for precision.
-Fiber's [`Ctx`](../api/ctx.md) now implements Go's +Fiber's [`Ctx`](../api/ctx.md) implements Go's [`context.Context`](https://pkg.go.dev/context#Context) interface. This means you can pass the context directly to functions that expect `context.Context` without any adapters. -However, due to current limitations in `fasthttp`, the -`Deadline`, `Done`, and `Err` methods are implemented as no-ops. +However, due to current limitations in `fasthttp`, the methods on `fiber.Ctx` +behave as follows: +- `Deadline` returns `(time.Time{}, false)`. +- `Done` returns `nil` (it never fires). +- `Err` returns `nil`.
37-47: Safer example and clarify Locals vs. WithValue propagation.
- The current snippet uses a blind type assertion that panics if the key is absent or not a string.
- It’s worth noting that
Localsare not propagated to derived contexts created viacontext.With*, and values added viacontext.WithValueare distinct fromLocals(even though both are visible throughValueonfiber.Ctx).-`Ctx.Value` is backed by [Locals](../api/ctx.md#locals). Values stored -with `c.Locals` can be read back via the `Value` method or through -`context.WithValue` helpers. +`Ctx.Value` is backed by [Locals](../api/ctx.md#locals). Values stored +with `c.Locals` can be read back via the `Value` method. Values attached with +`context.WithValue` are also visible through `c.Value`, but they are distinct +from `Locals` and `Locals` are not propagated to derived contexts. @@ app.Get("/", func(c fiber.Ctx) error { c.Locals("role", "admin") - role := c.Value("role") // returns "admin" - return c.SendString(role.(string)) + role, _ := c.Value("role").(string) // returns "admin" if present + return c.SendString(role) })
49-55: Consider linking to the fasthttpctx package/documentation.You mention the “fasthttpctx layer” without a pointer. If there’s a public package/doc page, linking it would help readers discover the exact API and import path.
If you confirm the public import path, I can add a precise link in a follow-up change.
154-171: Minor clarity: mention imports for the timeout example.Add a short note that this snippet requires
contextandtimeimports to reduce confusion when readers copy/paste.can wrap the request context when needed. ```go +// Requires: +// import "context" +// import "time" app.Get("/job", func(c fiber.Ctx) error { ctx, cancel := context.WithTimeout(c, 5*time.Second) defer cancel()
173-178: Add a note about context lifetime and goroutines.Readers often try to hold onto
fiber.Ctxbeyond the handler, which is unsafe. A short admonition here will prevent misuse.Even though the base `fiber.Ctx` never cancels on its own, wrapping it with helpers like `context.WithTimeout` creates a derived context that honors deadlines and cancellation for any operations you launch from the handler. This common pattern lets you coordinate work with external APIs or databases while keeping a familiar API. + +:::note +Do not store or use `fiber.Ctx` outside the lifetime of the handler. If you need +to pass context to a goroutine, derive a context (e.g., with `context.WithTimeout`) +and capture only the values you need. Ensure the work respects cancellation when +the handler returns. +:::
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled by default for public repositories
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (1)
docs/guide/context.md(1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
docs/**
📄 CodeRabbit Inference Engine (.github/copilot-instructions.md)
Review and update the contents of the
docsfolder if necessary when modifying code
Files:
docs/guide/context.md
🧠 Learnings (6)
📓 Common learnings
Learnt from: gaby
PR: gofiber/fiber#3193
File: middleware/cache/cache_test.go:897-897
Timestamp: 2024-11-08T04:10:42.990Z
Learning: In the Fiber framework, `Context()` is being renamed to `RequestCtx()`, and `UserContext()` to `Context()` to improve clarity and align with Go's context conventions.
Learnt from: gaby
PR: gofiber/fiber#3193
File: middleware/adaptor/adaptor.go:111-111
Timestamp: 2024-11-10T23:44:13.704Z
Learning: In the `middleware/adaptor/adaptor.go` file of the Fiber framework, when updating context handling, replacing `c.Context()` with `c.RequestCtx()` is appropriate to access the `fasthttp.RequestCtx`.
📚 Learning: 2024-11-10T23:44:13.704Z
Learnt from: gaby
PR: gofiber/fiber#3193
File: middleware/adaptor/adaptor.go:111-111
Timestamp: 2024-11-10T23:44:13.704Z
Learning: In the `middleware/adaptor/adaptor.go` file of the Fiber framework, when updating context handling, replacing `c.Context()` with `c.RequestCtx()` is appropriate to access the `fasthttp.RequestCtx`.
Applied to files:
docs/guide/context.md
📚 Learning: 2024-11-08T04:10:42.990Z
Learnt from: gaby
PR: gofiber/fiber#3193
File: middleware/cache/cache_test.go:897-897
Timestamp: 2024-11-08T04:10:42.990Z
Learning: In the Fiber framework, `Context()` is being renamed to `RequestCtx()`, and `UserContext()` to `Context()` to improve clarity and align with Go's context conventions.
Applied to files:
docs/guide/context.md
📚 Learning: 2024-11-29T12:37:27.581Z
Learnt from: efectn
PR: gofiber/fiber#3162
File: app_test.go:893-895
Timestamp: 2024-11-29T12:37:27.581Z
Learning: In the `Test_App_ShutdownWithContext` function in `app_test.go`, the `clientDone` channel is used to synchronize the client's request completion before proceeding, eliminating the need for additional `time.Sleep` calls.
Applied to files:
docs/guide/context.md
📚 Learning: 2024-10-08T19:06:06.583Z
Learnt from: hcancelik
PR: gofiber/fiber#3036
File: docs/middleware/cache.md:103-103
Timestamp: 2024-10-08T19:06:06.583Z
Learning: There are no hard tabs in the lines 100 to 105 of the `docs/middleware/cache.md` file. Future comments about formatting should accurately reflect the actual content.
Applied to files:
docs/guide/context.md
📚 Learning: 2024-09-25T16:15:39.392Z
Learnt from: sixcolors
PR: gofiber/fiber#3016
File: middleware/csrf/session_manager.go:30-43
Timestamp: 2024-09-25T16:15:39.392Z
Learning: In the session middleware, `session.FromContext(c)` returns `*session.Middleware`, whereas `m.session.Get(c)` returns `*session.Store`, so they are not directly interchangeable.
Applied to files:
docs/guide/context.md
🪛 LanguageTool
docs/guide/context.md
[grammar] ~12-~12: There might be a mistake here.
Context: ...: 4 --- import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; #...
(QB_NEW_EN)
[grammar] ~20-~20: There might be a mistake here.
Context: ... context.Context without any adapters. However, due to current limitations in `...
(QB_NEW_EN)
[grammar] ~21-~21: There might be a mistake here.
Context: ...o current limitations in fasthttp, the Deadline, Done, and Err methods ar...
(QB_NEW_EN)
[grammar] ~38-~38: There might be a mistake here.
Context: ...d back via the Value method or through context.WithValue helpers. ```go titl...
(QB_NEW_EN)
[grammar] ~53-~53: There might be a mistake here.
Context: ... and the context support provided by the fasthttpctx layer. ```go title="Acces...
(QB_NEW_EN)
[grammar] ~66-~66: There might be a mistake here.
Context: ...adline, Done is closed when the client connection ends, and once it fires Err...
(QB_NEW_EN)
[grammar] ~73-~73: There might be a mistake here.
Context: ...expose a number of helper functions that retrieve request-scoped values from the ...
(QB_NEW_EN)
[grammar] ~91-~91: There might be a mistake here.
Context: ...elpers to fetch the token or the handler attached to the current context. ```go ...
(QB_NEW_EN)
[grammar] ~157-~157: There might be a mistake here.
Context: ...xt.WithTimeout, or context.WithCancel` can wrap the request context when needed...
(QB_NEW_EN)
[grammar] ~175-~175: There might be a mistake here.
Context: ...ations you launch from the handler. This common pattern lets you coordinate work ...
(QB_NEW_EN)
[grammar] ~176-~176: There might be a mistake here.
Context: ...rk with external APIs or databases while keeping a familiar API. ## Summary - `...
(QB_NEW_EN)
[grammar] ~184-~184: There might be a mistake here.
Context: ...loses when the client connection ends. - Middleware helpers like `requestid.FromC...
(QB_NEW_EN)
[grammar] ~186-~186: There might be a mistake here.
Context: ...it easy to retrieve request-scoped data. - Standard helpers such as `context.WithTi...
(QB_NEW_EN)
🔇 Additional comments (4)
docs/guide/context.md (4)
65-70: Accurate description of RequestCtx.Done behavior.This correctly states that
Donecloses on client disconnect and thatErrreportscontext.Canceledafter it fires. This addresses prior concerns about inaccuracies.
102-112: Nice, more practical CSRF example.Wrapping the delete-token logic in a logout handler improves clarity and matches common usage.
181-188: Well-scoped, accurate summary.Concise and correct: distinguishes
fiber.Ctxno-op methods fromRequestCtx.Doneon disconnect, and points readers to helper functions and derived contexts.
116-126: *Incorrect —session.FromContext(c)returns Middleware; the docs example is correct.FromContext's signature (middleware/session/middleware.go) returns *Middleware, and Middleware implements Get/Set/Delete/ID/Fresh/Store which forward to the underlying *Session, so calling sess.Get("visits") is valid.
Relevant locations:
- middleware/session/middleware.go — func FromContext(c fiber.Ctx) *Middleware and methods on *Middleware (Get, Set, Delete, ID, Fresh, Store).
- middleware/session/session.go — Session struct and its Get/Set/etc implementations.
- middleware/session/middleware_test.go — real usage examples calling sess.Get(), sess.ID(), sess.Fresh(), sess.Store().
Conclusion: No change needed to docs/guide/context.md; the snippet is correct.
Likely an incorrect or invalid review comment.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
♻️ Duplicate comments (1)
docs/guide/context.md (1)
102-102: Retitle code block for clearer contextMake the example’s purpose immediately obvious in the sidebar/code block header.
-```go title="Deleting a token" +```go title="Deleting a token on logout"
🧹 Nitpick comments (5)
docs/guide/context.md (5)
12-14: Remove unused Docusaurus importsTabs/TabItem are imported but not used on this page.
Apply this diff to drop the unused imports:
-import Tabs from '@theme/Tabs'; -import TabItem from '@theme/TabItem';
21-23: Be explicit about the “no-op” semantics on fiber.CtxSpell out the exact behaviors to avoid ambiguity for readers who expect Go’s context semantics.
Apply this wording update:
-However, due to current limitations in `fasthttp`, the -`Deadline`, `Done`, and `Err` methods are implemented as no-ops. +However, due to current limitations in `fasthttp`, the `Deadline`, `Done`, and `Err` +methods are effectively no-ops: `Deadline` returns (time.Time{}, false), `Done` never +closes (returns nil), and `Err` is always nil.
41-47: Use a safe type assertion in the exampleDefensive assertion avoids panics if the stored value’s type changes in edits or copy/paste scenarios.
Suggested tweak:
app.Get("/", func(c fiber.Ctx) error { c.Locals("role", "admin") - role := c.Value("role") // returns "admin" - return c.SendString(role.(string)) + role := c.Value("role") + s, ok := role.(string) + if !ok { + return fiber.ErrInternalServerError + } + return c.SendString(s) })
154-171: Optional: Show imports in the timeout exampleMinor clarity improvement for copy/paste usability.
You could prepend the example with:
import ( "context" "time" )
181-188: Mirror the precise “no-op” wording in SummaryAlign the bullets with the explicit semantics suggested above.
-- `fiber.Ctx` satisfies `context.Context` but its `Deadline`, `Done`, and `Err` - methods are currently no-ops. +- `fiber.Ctx` satisfies `context.Context`, but `Deadline` returns (time.Time{}, false), + `Done` never closes (nil), and `Err` is always nil.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled by default for public repositories
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (1)
docs/guide/context.md(1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
docs/**
📄 CodeRabbit Inference Engine (.github/copilot-instructions.md)
Review and update the contents of the
docsfolder if necessary when modifying code
Files:
docs/guide/context.md
🧠 Learnings (6)
📓 Common learnings
Learnt from: gaby
PR: gofiber/fiber#3193
File: middleware/cache/cache_test.go:897-897
Timestamp: 2024-11-08T04:10:42.990Z
Learning: In the Fiber framework, `Context()` is being renamed to `RequestCtx()`, and `UserContext()` to `Context()` to improve clarity and align with Go's context conventions.
Learnt from: gaby
PR: gofiber/fiber#3193
File: middleware/adaptor/adaptor.go:111-111
Timestamp: 2024-11-10T23:44:13.704Z
Learning: In the `middleware/adaptor/adaptor.go` file of the Fiber framework, when updating context handling, replacing `c.Context()` with `c.RequestCtx()` is appropriate to access the `fasthttp.RequestCtx`.
📚 Learning: 2024-11-10T23:44:13.704Z
Learnt from: gaby
PR: gofiber/fiber#3193
File: middleware/adaptor/adaptor.go:111-111
Timestamp: 2024-11-10T23:44:13.704Z
Learning: In the `middleware/adaptor/adaptor.go` file of the Fiber framework, when updating context handling, replacing `c.Context()` with `c.RequestCtx()` is appropriate to access the `fasthttp.RequestCtx`.
Applied to files:
docs/guide/context.md
📚 Learning: 2024-11-08T04:10:42.990Z
Learnt from: gaby
PR: gofiber/fiber#3193
File: middleware/cache/cache_test.go:897-897
Timestamp: 2024-11-08T04:10:42.990Z
Learning: In the Fiber framework, `Context()` is being renamed to `RequestCtx()`, and `UserContext()` to `Context()` to improve clarity and align with Go's context conventions.
Applied to files:
docs/guide/context.md
📚 Learning: 2024-11-29T12:37:27.581Z
Learnt from: efectn
PR: gofiber/fiber#3162
File: app_test.go:893-895
Timestamp: 2024-11-29T12:37:27.581Z
Learning: In the `Test_App_ShutdownWithContext` function in `app_test.go`, the `clientDone` channel is used to synchronize the client's request completion before proceeding, eliminating the need for additional `time.Sleep` calls.
Applied to files:
docs/guide/context.md
📚 Learning: 2024-10-08T19:06:06.583Z
Learnt from: hcancelik
PR: gofiber/fiber#3036
File: docs/middleware/cache.md:103-103
Timestamp: 2024-10-08T19:06:06.583Z
Learning: There are no hard tabs in the lines 100 to 105 of the `docs/middleware/cache.md` file. Future comments about formatting should accurately reflect the actual content.
Applied to files:
docs/guide/context.md
📚 Learning: 2024-10-08T19:06:06.583Z
Learnt from: sixcolors
PR: gofiber/fiber#3016
File: middleware/csrf/session_manager.go:30-43
Timestamp: 2024-10-08T19:06:06.583Z
Learning: In the session middleware, `session.FromContext(c)` returns `*session.Middleware`, whereas `m.session.Get(c)` returns `*session.Store`, so they are not directly interchangeable.
Applied to files:
docs/guide/context.md
🪛 LanguageTool
docs/guide/context.md
[grammar] ~12-~12: There might be a mistake here.
Context: ...: 4 --- import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem'; #...
(QB_NEW_EN)
[grammar] ~20-~20: There might be a mistake here.
Context: ... context.Context without any adapters. However, due to current limitations in `...
(QB_NEW_EN)
[grammar] ~21-~21: There might be a mistake here.
Context: ...o current limitations in fasthttp, the Deadline, Done, and Err methods ar...
(QB_NEW_EN)
[grammar] ~38-~38: There might be a mistake here.
Context: ...d back via the Value method or through context.WithValue helpers. ```go titl...
(QB_NEW_EN)
[grammar] ~53-~53: There might be a mistake here.
Context: ... and the context support provided by the fasthttpctx layer. ```go title="Acces...
(QB_NEW_EN)
[grammar] ~66-~66: There might be a mistake here.
Context: ...adline, Done is closed when the client connection ends, and once it fires Err...
(QB_NEW_EN)
[grammar] ~73-~73: There might be a mistake here.
Context: ...expose a number of helper functions that retrieve request-scoped values from the ...
(QB_NEW_EN)
[grammar] ~91-~91: There might be a mistake here.
Context: ...elpers to fetch the token or the handler attached to the current context. ```go ...
(QB_NEW_EN)
[grammar] ~157-~157: There might be a mistake here.
Context: ...xt.WithTimeout, or context.WithCancel` can wrap the request context when needed...
(QB_NEW_EN)
[grammar] ~175-~175: There might be a mistake here.
Context: ...ations you launch from the handler. This common pattern lets you coordinate work ...
(QB_NEW_EN)
[grammar] ~176-~176: There might be a mistake here.
Context: ...rk with external APIs or databases while keeping a familiar API. ## Summary - `...
(QB_NEW_EN)
[grammar] ~184-~184: There might be a mistake here.
Context: ...loses when the client connection ends. - Middleware helpers like `requestid.FromC...
(QB_NEW_EN)
[grammar] ~186-~186: There might be a mistake here.
Context: ...it easy to retrieve request-scoped data. - Standard helpers such as `context.WithTi...
(QB_NEW_EN)
🔇 Additional comments (5)
docs/guide/context.md (5)
49-55: Good clarification on accessing fasthttp.RequestCtxClear link and usage of c.RequestCtx() matches current naming and aligns with prior renaming from Context() to RequestCtx().
65-70: Accurate description of fasthttpctx Done/Err semanticsNice job stating that Done() closes on client disconnect and Err becomes context.Canceled. This corrects a common misconception and is exactly what users need to know.
146-151: TokenFromContext returns only a string – verified in middleware/keyauth/keyauth.go (line 72) that its signature isfunc TokenFromContext(c fiber.Ctx) string. There’s noboolreturn, so the example can remain unchanged.
133-138: Nookcheck needed for UsernameFromContext
Verified thatUsernameFromContext(c fiber.Ctx)is declared asfunc UsernameFromContext(c fiber.Ctx) stringand returns an empty string when no username is found. The existing example is therefore correct.
116-126: Session.FromContext returns a Middleware with Get – example is accurateVerified that
session.FromContext(c)is defined as:func FromContext(c fiber.Ctx) *Middlewareand that
*Middlewareimplementsfunc (m *Middleware) Get(key any) anyso the usage in
docs/guide/context.mdis correct and needs no changes.
Summary
context.Contextfasthttp.RequestCtxandfasthttpctxrequestid.FromContext