-
-
Notifications
You must be signed in to change notification settings - Fork 1.9k
📘 docs(context): add goroutine cancellation example using context.WithTimeout #3884
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
|
Thanks for opening this pull request! 🎉 Please check out our contributing guidelines. If you need help or want to chat with us, join us on Discord https://gofiber.io/discord |
|
Caution Review failedThe pull request is closed. 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. WalkthroughAdded a new subsection "Context Cancellation with Goroutines in Fiber" to docs/guide/context.md demonstrating deriving a timeout-aware stdlib context from Fiber's Changes
Sequence Diagram(s)sequenceDiagram
participant Client
participant Handler as Fiber Handler
participant Ctx as ctx (WithTimeout)
participant Worker as Goroutine Worker
Client->>Handler: HTTP request
Handler->>Ctx: derive ctx = context.WithTimeout(c.Context(), 3s)
Handler->>Worker: start worker(ctx, resultCh)
note right of Worker `#DDEEFF`: Worker listens on ctx.Done() and stops work
Worker-->>Handler: send result on resultCh (if completed)
alt result before timeout
Handler->>Client: 200 OK (result)
else ctx.Done() / timeout
Handler->>Client: 504 Gateway Timeout
end
Estimated code review effort🎯 2 (Simple) | ⏱️ ~10 minutes
Possibly related PRs
Suggested reviewers
Poem
Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
📜 Recent review detailsConfiguration used: CodeRabbit UI Review profile: CHILL Plan: Pro 📒 Files selected for processing (1)
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. Comment |
Summary of ChangesHello @BigJoe17, 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 enhances the documentation by adding a comprehensive guide on managing context cancellation with goroutines within Fiber applications. The new section provides crucial information and a code example to help developers correctly handle asynchronous operations, ensuring that long-running tasks respect request timeouts and client disconnections, thereby preventing resource leaks and improving application robustness. Highlights
Using Gemini Code AssistThe 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
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 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
|
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 helpful example for context cancellation with goroutines. I've suggested a small improvement to the code example to better illustrate how a long-running task can be made cancellable, which aligns more closely with the accompanying explanation about exiting early.
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 documentation for context cancellation patterns when using goroutines in Fiber handlers. It demonstrates how to properly handle timeouts and cancellation signals in asynchronous work.
- Adds a new subsection explaining context cancellation with goroutines
- Provides a complete code example showing timeout handling and channel-based communication
- Explains the pattern for preventing resource leaks in long-running operations
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: 1
🧹 Nitpick comments (2)
docs/guide/context.md (2)
219-220: Clarify the goroutine's cancellation mechanism.The phrasing "checks
ctx.Done()before sending a result" is imprecise. The code actually uses aselectstatement to race between receiving the done signal and sending the result. The wording could better reflect this.Consider rephrasing to something like:
"The goroutine uses a select statement to race between
ctx.Done()and sending its result. If the timeout fires first, the done channel closes and the goroutine exits; otherwise it sends the result."
237-244: Add a clarifying comment about the timeout-driven example flow.The goroutine sleeps for 3 seconds while the timeout is 2 seconds, so the context cancellation will fire before the sleep completes. The second case (
resultChan <- "done") will rarely execute in this specific example. Adding a brief inline comment would help readers understand this is intentional—to demonstrate how handlers react to timeouts before goroutines finish.Consider adding a comment like:
go func() { time.Sleep(3 * time.Second) // longer than timeout; demonstrates timeout handling select { case <-ctx.Done(): return case resultChan <- "done": } }()
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
docs/guide/context.md(1 hunks)
🧰 Additional context used
🧠 Learnings (7)
📓 Common learnings
Learnt from: efectn
Repo: gofiber/fiber PR: 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.
Learnt from: laughing-nerd
Repo: gofiber/fiber PR: 3775
File: middleware/limiter/limiter_test.go:237-245
Timestamp: 2025-10-03T21:06:01.416Z
Learning: In Go 1.25.0, the sync.WaitGroup type gained a new Go method that launches a goroutine and automatically handles Add/Done calls, eliminating the need for manual wg.Add(1) and defer wg.Done() patterns. The method signature is func (wg *WaitGroup) Go(f func()). This is a valid and preferred pattern for Go 1.25.0+ codebases.
Learnt from: gaby
Repo: gofiber/fiber PR: 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`.
Learnt from: gaby
Repo: gofiber/fiber PR: 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: laughing-nerd
Repo: gofiber/fiber PR: 3775
File: client/client_test.go:330-334
Timestamp: 2025-10-03T21:02:23.608Z
Learning: In Go 1.25.0 and later, sync.WaitGroup has a Go(func()) method that combines wg.Add(1) and launching a goroutine, eliminating the need for the traditional wg.Add(1); go func() { defer wg.Done(); ... }() pattern. This is valid and idiomatic for Go 1.25.0+ codebases.
Learnt from: laughing-nerd
Repo: gofiber/fiber PR: 3775
File: middleware/idempotency/idempotency_test.go:122-125
Timestamp: 2025-10-03T21:02:49.650Z
Learning: Go 1.25.0 introduced sync.WaitGroup.Go(f func()) method that automatically increments the WaitGroup counter before starting f in a new goroutine and decrements it when f returns. This is the preferred pattern over manual Add/Done calls in Go 1.25.0+.
📚 Learning: 2024-11-08T04:10:42.990Z
Learnt from: gaby
Repo: gofiber/fiber PR: 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-10T23:44:13.704Z
Learnt from: gaby
Repo: gofiber/fiber PR: 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-29T12:37:27.581Z
Learnt from: efectn
Repo: gofiber/fiber PR: 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-11-15T07:56:21.623Z
Learnt from: ReneWerner87
Repo: gofiber/fiber PR: 3161
File: app.go:923-932
Timestamp: 2024-11-15T07:56:21.623Z
Learning: In the Fiber framework, breaking changes are acceptable when moving from version 2 to version 3, including modifications to method signatures such as in the `Test` method in `app.go`.
Applied to files:
docs/guide/context.md
📚 Learning: 2024-10-08T19:06:06.583Z
Learnt from: sixcolors
Repo: gofiber/fiber PR: 3016
File: middleware/session/config.go:122-122
Timestamp: 2024-10-08T19:06:06.583Z
Learning: In `DefaultErrorHandler(c *fiber.Ctx, err error)`, since `c` is a pointer to an interface, we need to dereference `*c` when calling interface methods like `SendStatus`.
Applied to files:
docs/guide/context.md
📚 Learning: 2025-10-16T07:15:26.529Z
Learnt from: grivera64
Repo: gofiber/fiber PR: 3807
File: adapter_test.go:118-144
Timestamp: 2025-10-16T07:15:26.529Z
Learning: In Fiber v3, net/http handlers (http.Handler, http.HandlerFunc, or raw func(http.ResponseWriter, *http.Request)) can be passed directly to routing methods like app.Get(), app.Post(), etc. The framework automatically detects and wraps them internally via toFiberHandler/collectHandlers. The github.com/gofiber/fiber/v3/middleware/adaptor package is legacy and should not be suggested for tests or code using native net/http handler support.
Applied to files:
docs/guide/context.md
|
@BigJoe17 thx for the PR |
|
alright @ReneWerner87 I just updated the Markdown lint and added it |
|
@BigJoe17 markdown lint still fails And could you please check the review comments? There may be some improvements to be made. |
|
Congrats on merging your first pull request! 🎉 We here at Fiber are proud of you! If you need help or want to chat with us, join us on Discord https://gofiber.io/discord |

Description
This PR adds an example showing how to run goroutines inside a Fiber handler using a derived context created with
context.WithTimeout.The example demonstrates how to:
ctx.Done()504 Gateway Timeoutwhen the deadline expiresThis fills a gap in the documentation and helps developers integrate Fiber with context-aware APIs.
Commit formatting
Please use emojis in commit messages for an easy way to identify the purpose or intention of a commit. Check out the emoji cheatsheet here: CONTRIBUTING.md