Skip to content

Conversation

@gaby
Copy link
Member

@gaby gaby commented Aug 11, 2025

Summary

  • document Fiber's Ctx as a context.Context
  • explain using fasthttp.RequestCtx and fasthttpctx
  • cover helper functions like requestid.FromContext

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 11, 2025

Note

Other AI code review bot(s) detected

CodeRabbit 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.

Walkthrough

Adds a new documentation page explaining that fiber.Ctx implements context.Context, describes fasthttp/fasthttpctx semantics for Deadline/Done/Err, shows accessing the underlying fasthttp.RequestCtx, documents middleware context helpers, and provides examples for deriving and passing contexts in handlers.

Changes

Cohort / File(s) Summary
Docs: Context guide
docs/guide/context.md
New guide explaining fiber.Ctx as context.Context, fasthttpctx semantics (no deadline; Done closes on client disconnect; Err reports cancellation), RequestCtx() access, middleware helpers (requestid, csrf, session, basicauth, keyauth), deriving contexts (e.g., context.WithTimeout), and multiple usage examples.

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
Loading

Estimated code review effort

🎯 1 (Trivial) | ⏱️ ~2 minutes

Possibly related PRs

Suggested labels

v3

Suggested reviewers

  • sixcolors
  • ReneWerner87
  • efectn

Poem

Hop hop, I pass the Ctx along,
From handler burrow to timeout song,
Done wakes when the client has gone,
Locals keep secrets all day long,
A carrot of docs to munch along. 🥕

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
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch 2025-08-11-13-54-03

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

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.

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 Ctx and context.Context integration: The new guide explains that fiber.Ctx now implements Go's context.Context interface, allowing direct passing to functions expecting context.Context. It also notes the current fasthttp limitations where Deadline, Done, and Err methods are no-ops.
  • fasthttp.RequestCtx and fasthttpctx usage: The documentation details how to access the underlying fasthttp.RequestCtx via c.RequestCtx() for low-level API access and clarifies how fasthttpctx enables fasthttp to satisfy context.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, and keyauth.TokenFromContext.
  • Integrating with context.WithValue and friends: It demonstrates how standard context package helpers like context.WithValue, context.WithTimeout, and context.WithCancel can be used to wrap the request context, emphasizing consistent API usage and future-proofing despite current fasthttp limitations.
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

  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.

@gaby gaby changed the title docs: add context guide 📒 docs: Add context guide Aug 11, 2025
@gaby gaby added this to v3 Aug 11, 2025
@gaby gaby added this to the v3 milestone Aug 11, 2025
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 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.

@gaby
Copy link
Member Author

gaby commented Aug 15, 2025

/gemini review

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 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>
@gaby gaby marked this pull request as ready for review August 15, 2025 03:14
Copilot AI review requested due to automatic review settings August 15, 2025 03:14
@gaby gaby requested a review from a team as a code owner August 15, 2025 03:14
Copy link
Contributor

Copilot AI left a 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 Ctx as implementing context.Context with current limitations
  • Explains accessing the underlying fasthttp.RequestCtx and fasthttpctx layer
  • Provides examples of context helper functions from various middleware packages

Copy link
Contributor

@coderabbitai coderabbitai bot left a 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.Value reads values set via a derived context. In practice, c.Value is backed by Locals, while context.WithValue(c, ...) returns a derived context whose values are read via that returned context, not c.

-`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 attribute Done semantics to fasthttp.RequestCtx and link precisely.

The semantics (no deadline; Done closes on client disconnect; Err becomes context.Canceled) are properties of fasthttp.RequestCtx’s context.Context implementation. 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 use c.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.

📥 Commits

Reviewing files that changed from the base of the PR and between e7b0508 and bb41229.

📒 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 docs folder 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)

Copy link
Contributor

@coderabbitai coderabbitai bot left a 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 Locals are not propagated to derived contexts created via context.With*, and values added via context.WithValue are distinct from Locals (even though both are visible through Value on fiber.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 context and time imports 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.Ctx beyond 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.

📥 Commits

Reviewing files that changed from the base of the PR and between bb41229 and 874ffbb.

📒 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 docs folder 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 Done closes on client disconnect and that Err reports context.Canceled after 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.Ctx no-op methods from RequestCtx.Done on 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.

Copy link
Contributor

@coderabbitai coderabbitai bot left a 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 context

Make 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 imports

Tabs/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.Ctx

Spell 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 example

Defensive 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 example

Minor clarity improvement for copy/paste usability.

You could prepend the example with:

import (
    "context"
    "time"
)

181-188: Mirror the precise “no-op” wording in Summary

Align 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.

📥 Commits

Reviewing files that changed from the base of the PR and between 874ffbb and cef48b2.

📒 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 docs folder 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.RequestCtx

Clear 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 semantics

Nice 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 is func TokenFromContext(c fiber.Ctx) string. There’s no bool return, so the example can remain unchanged.


133-138: No ok check needed for UsernameFromContext
Verified that UsernameFromContext(c fiber.Ctx) is declared as

func UsernameFromContext(c fiber.Ctx) string

and 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 accurate

Verified that session.FromContext(c) is defined as:

func FromContext(c fiber.Ctx) *Middleware

and that *Middleware implements

func (m *Middleware) Get(key any) any

so the usage in docs/guide/context.md is correct and needs no changes.

@ReneWerner87 ReneWerner87 merged commit 6984b5d into main Aug 19, 2025
2 checks passed
@ReneWerner87 ReneWerner87 deleted the 2025-08-11-13-54-03 branch August 19, 2025 06:37
@github-project-automation github-project-automation bot moved this to Done in v3 Aug 19, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

4 participants