Skip to content

Conversation

@BigJoe17
Copy link
Contributor

@BigJoe17 BigJoe17 commented Nov 20, 2025

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:

  • avoid goroutine leaks by checking ctx.Done()
  • return a 504 Gateway Timeout when the deadline expires
  • safely run long-running operations inside Fiber handlers

This 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

@BigJoe17 BigJoe17 requested a review from a team as a code owner November 20, 2025 06:25
@welcome
Copy link

welcome bot commented Nov 20, 2025

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

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Nov 20, 2025

Caution

Review failed

The pull request is closed.

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

Added a new subsection "Context Cancellation with Goroutines in Fiber" to docs/guide/context.md demonstrating deriving a timeout-aware stdlib context from Fiber's Ctx, running goroutines that respect ctx.Done(), returning HTTP 504 on timeout, and providing a runnable Go example with proper cancellation to avoid leaks.

Changes

Cohort / File(s) Change Summary
Documentation Addition
docs/guide/context.md
Added "Context Cancellation with Goroutines in Fiber" section showing how to derive a context.WithTimeout from Fiber's Ctx, start a cancellation-aware goroutine that selects on ctx.Done(), coordinate via a result channel, return 504 on timeout, and include a runnable Go example with defer cancel() to prevent leaks.

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
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

  • Review the example's use of context.WithTimeout and defer cancel().
  • Verify the goroutine correctly selects on ctx.Done() and closes channels / returns to avoid leaks.
  • Check doc wording accurately references Fiber's ability to derive/use a stdlib context.Context.

Possibly related PRs

Suggested reviewers

  • gaby
  • sixcolors
  • efectn

Poem

🐰 I hopped into code with timeout in paw,
I watched for ctx.Done and obeyed every law.
If work took too long and the timer did chime,
A tidy 504 closed the queue in good time.
No leaks, just clean hops — I munched on a thyme. 🥕

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Description check ⚠️ Warning The description explains the purpose and changes but lacks required template sections like 'Changes introduced' checklist and 'Type of change' selection, which are mandatory per the repository template. Complete the PR description by filling out the 'Changes introduced' checklist (mark Documentation Update), select 'Documentation update' under 'Type of change', and complete the verification checklist items where applicable.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly describes the main change: adding a goroutine cancellation example using context.WithTimeout in the documentation. It directly relates to the actual documentation update provided.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 410fedc and 0372cca.

📒 Files selected for processing (1)
  • docs/guide/context.md (1 hunks)

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

❤️ Share

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

@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello @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

  • Documentation Update: Added a new section to the context.md guide explaining how to implement context cancellation with goroutines in Fiber handlers to prevent resource leaks for asynchronous operations.
  • Code Example: Included a practical Go code example demonstrating the use of context.WithTimeout and select statements to manage goroutine lifecycle based on request context cancellation.
Using Gemini Code Assist

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

Invoking Gemini

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

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

Customization

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

Limitations & Feedback

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

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

Footnotes

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

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

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

@BigJoe17 BigJoe17 changed the title docs(context): add cancellation example with goroutines docs(context): add goroutine cancellation example using context.WithTimeout Nov 20, 2025
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: 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 a select statement 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

📥 Commits

Reviewing files that changed from the base of the PR and between fa42d1f and eebfa83.

📒 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 BigJoe17 changed the title docs(context): add goroutine cancellation example using context.WithTimeout 📘 docs(context): add goroutine cancellation example using context.WithTimeout Nov 20, 2025
@ReneWerner87
Copy link
Member

@BigJoe17 thx for the PR
can you check the markdown linting and also the AI hints

@BigJoe17
Copy link
Contributor Author

alright @ReneWerner87 I just updated the Markdown lint and added it

@ReneWerner87
Copy link
Member

@BigJoe17 markdown lint still fails
image

And could you please check the review comments? There may be some improvements to be made.

@ReneWerner87 ReneWerner87 merged commit 9c2b399 into gofiber:main Dec 7, 2025
4 of 5 checks passed
@welcome
Copy link

welcome bot commented Dec 7, 2025

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

@github-project-automation github-project-automation bot moved this to Done in v3 Dec 7, 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.

2 participants