Skip to content

📒 docs: Improve Timeout middleware documentation#3675

Merged
ReneWerner87 merged 3 commits intomainfrom
2025-08-10-19-16-50
Aug 11, 2025
Merged

📒 docs: Improve Timeout middleware documentation#3675
ReneWerner87 merged 3 commits intomainfrom
2025-08-10-19-16-50

Conversation

@gaby
Copy link
Member

@gaby gaby commented Aug 10, 2025

Summary

  • clarify what the timeout middleware does
  • add a full runnable example and curl instructions
  • warn against registering the timeout middleware with app.Use, which will panic

Fixes #3674

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 10, 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

The documentation for the Fiber timeout middleware was rewritten for clarity and completeness. It now details middleware behavior, usage constraints, and proper handler wrapping. A new, runnable example demonstrates timeout handling and context cancellation. Headings, formatting, and code samples were updated, and cautionary notes about correct usage were added.

Changes

Cohort / File(s) Change Summary
Timeout Middleware Documentation
docs/middleware/timeout.md
Rewrote and expanded documentation for the timeout middleware, clarified behavior, usage, and added a runnable example. Improved formatting and added cautionary notes on usage constraints.

Sequence Diagram(s)

Not applicable: Only documentation and example code changes were made.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~7 minutes

Assessment against linked issues

Objective Addressed Explanation
Clarify correct usage of timeout middleware to prevent panic when used globally or incorrectly (#3674)
Warn that timeout middleware must wrap route handlers, not be used with app.Use or in middleware chains (#3674)
Provide an example demonstrating proper usage and context cancellation awareness (#3674)

Assessment against linked issues: Out-of-scope changes

No out-of-scope changes were found.

Suggested reviewers

  • sixcolors
  • efectn

Poem

A timeout tale, rewritten anew,
With context, warnings, and examples too!
No more panics, no more dread,
Just read the docs and forge ahead.
🐇✨
In Fiber’s warren, bugs take flight—
Clear docs guide you to code it right!

Note

🔌 MCP (Model Context Protocol) integration is now available in Early Access!

Pro users can now connect to remote MCP servers under the Integrations page to get reviews and chat conversations that understand additional development context.

✨ Finishing Touches
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch 2025-08-10-19-16-50

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.
    • Explain this complex logic.
    • 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. Examples:
    • @coderabbitai explain this code block.
  • 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 src/utils.ts and explain its main purpose.
    • @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 comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

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

Documentation and Community

  • 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'm enhancing the documentation for the timeout middleware. This PR clarifies its purpose, provides a comprehensive runnable example with curl instructions, removes outdated information, and adds a crucial warning about its improper usage with app.Use.

Highlights

  • Clarified Timeout Middleware Purpose: I've updated the introductory text to clearly explain what the timeout middleware does and how it uses context.WithTimeout.
  • Added Comprehensive Example: I've included a full, runnable Go example demonstrating the timeout middleware, complete with curl commands for testing both successful and timed-out requests.
  • Removed Outdated Information: I've removed notes referring to previous or distinct implementations of the timeout middleware, streamlining the guide.
  • Added Usage Warning: I've added a prominent caution against using timeout.New with app.Use and explained the potential panic if c.Next() is called inside the wrapped handler.
  • Improved Example Structure: I've reformatted existing examples (custom error, DB call) to be consistent subheadings.
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 added the v3 label Aug 10, 2025
@gaby gaby added this to v3 Aug 10, 2025
@gaby gaby added this to the v3 milestone Aug 10, 2025
@gaby gaby moved this to In Progress in v3 Aug 10, 2025
@gaby gaby changed the title docs: expand timeout middleware guide 📒 docs: Improve Timeout middleware documentation Aug 10, 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 significantly improves the documentation for the timeout middleware. The explanation of the middleware's purpose is now clearer, and it includes a crucial warning about its correct usage. The old, fragmented example has been replaced with a complete, runnable Go program, including curl commands for testing, which is a great enhancement for users. I've found one minor issue in the new example where an error is ignored, which could be improved to demonstrate better error handling practices.

@gaby gaby marked this pull request as ready for review August 10, 2025 19:18
Copilot AI review requested due to automatic review settings August 10, 2025 19:18
@gaby gaby requested a review from a team as a code owner August 10, 2025 19:18
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 improves the timeout middleware documentation to make it clearer and more user-friendly. It addresses confusion about how the middleware works and provides better guidance on proper usage.

Key changes:

  • Replaced vague explanations with clear description of timeout behavior and context cancellation
  • Added comprehensive runnable example with curl test instructions
  • Added warning about incorrect usage with app.Use() that causes panics

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
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

🔭 Outside diff range comments (1)
docs/middleware/timeout.md (1)

129-141: Improve DB example: error handling and transaction rollback

  • Check and handle errors from gorm.Open/Begin.
  • Roll back on any failure to avoid leaving open transactions.
  • Keep the context usage as-is.
-    handler := func(ctx fiber.Ctx) error {
-        tran := db.WithContext(ctx.Context()).Begin()
-        
-        if tran = tran.Exec("SELECT pg_sleep(50)"); tran.Error != nil {
-            return tran.Error
-        }
-        
-        if tran = tran.Commit(); tran.Error != nil {
-            return tran.Error
-        }
-
-        return nil
-    }
+    handler := func(ctx fiber.Ctx) error {
+        tx := db.WithContext(ctx.Context()).Begin()
+        if tx.Error != nil {
+            return tx.Error
+        }
+        if err := tx.Exec("SELECT pg_sleep(50)").Error; err != nil {
+            _ = tx.Rollback().Error
+            return err
+        }
+        if err := tx.Commit().Error; err != nil {
+            _ = tx.Rollback().Error
+            return err
+        }
+        return nil
+    }
♻️ Duplicate comments (2)
docs/middleware/timeout.md (2)

97-101: Handle parse errors consistently

Mirror the basic example: validate sleepTime and return 400 on bad input.

-        sleepTime, _ := time.ParseDuration(c.Params("sleepTime") + "ms")
+        sleepStr := c.Params("sleepTime")
+        sleepTime, err := time.ParseDuration(sleepStr + "ms")
+        if err != nil {
+            return fiber.NewError(fiber.StatusBadRequest, "invalid sleepTime")
+        }

57-63: Handle parse errors and flip error-wrapping order

  • Return 400 on invalid delay instead of ignoring the error.
  • Prefer “context: %w” ordering for error wrapping.
-    handler := func(c fiber.Ctx) error {
-        delay, _ := time.ParseDuration(c.Params("delay") + "ms")
-        if err := sleepWithContext(c.Context(), delay); err != nil {
-            return fmt.Errorf("%w: execution error", err)
-        }
-        return c.SendString("finished")
-    }
+    handler := func(c fiber.Ctx) error {
+        delayStr := c.Params("delay")
+        delay, err := time.ParseDuration(delayStr + "ms")
+        if err != nil {
+            return fiber.NewError(fiber.StatusBadRequest, "invalid delay")
+        }
+        if err := sleepWithContext(c.Context(), delay); err != nil {
+            return fmt.Errorf("execution error: %w", err)
+        }
+        return c.SendString("finished")
+    }
🧹 Nitpick comments (5)
docs/middleware/timeout.md (5)

7-10: Clarify cancellation requirement for handlers

Add an explicit note that handlers must actively observe c.Context().Done() and stop work, otherwise the goroutine may continue running even after the 408 is sent.


12-16: Strengthen “Do/Don’t” with explicit examples

Consider adding a small “Do vs Don’t” snippet to make misuse obvious.

// Don't: global use (will panic)
app.Use(timeout.New(h))

// Do: wrap the final handler per route
app.Get("/foo", timeout.New(h, timeout.Config{Timeout: 2 * time.Second}))

33-52: Avoid potential timer leak; prefer time.NewTimer with stop/drain

Using time.After prevents canceling the timer if the context fires first. Suggest using time.NewTimer and stopping/draining it on cancellation.

-func sleepWithContext(ctx context.Context, d time.Duration) error {
-    select {
-    case <-time.After(d):
-        return nil
-    case <-ctx.Done():
-        return ctx.Err()
-    }
-}
+func sleepWithContext(ctx context.Context, d time.Duration) error {
+    timer := time.NewTimer(d)
+    defer func() {
+        if !timer.Stop() {
+            <-timer.C
+        }
+    }()
+    select {
+    case <-timer.C:
+        return nil
+    case <-ctx.Done():
+        return ctx.Err()
+    }
+}

73-78: Optional: show explicit timeout behavior in curl

Consider adding examples with timing to make the difference visible:

time curl -s -o /dev/null -w "%{http_code}\n" http://localhost:3000/sleep/1000
time curl -s -o /dev/null -w "%{http_code}\n" http://localhost:3000/sleep/3000

125-128: Optional: acknowledge omitted imports for partial snippet

Consider a brief note that imports/DSN handling are omitted for brevity, consistent with other Fiber docs.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9ca6ebd and 3af419d.

📒 Files selected for processing (1)
  • docs/middleware/timeout.md (4 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/middleware/timeout.md
🧠 Learnings (2)
📓 Common learnings
Learnt from: sixcolors
PR: gofiber/fiber#3446
File: docs/middleware/logger.md:44-44
Timestamp: 2025-05-13T00:19:16.407Z
Learning: In documentation files for the Fiber framework, code examples are often partial and don't repeat import statements that were shown in earlier examples, focusing instead on demonstrating specific usage patterns.
📚 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/middleware/timeout.md
🔇 Additional comments (5)
docs/middleware/timeout.md (5)

26-31: LGTM: clear intro for the basic example


65-67: LGTM: per-route wrapping with explicit timeout


89-89: LGTM: clearer heading


108-119: LGTM: robust timer handling pattern

Good use of time.NewTimer with proper stop/drain.


122-122: LGTM: heading capitalization is consistent

@ReneWerner87 ReneWerner87 merged commit 40e1e76 into main Aug 11, 2025
2 checks passed
@ReneWerner87 ReneWerner87 deleted the 2025-08-10-19-16-50 branch August 11, 2025 10:28
@github-project-automation github-project-automation bot moved this from In Progress to Done in v3 Aug 11, 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.

🐛 [Bug]: Middleware timeout returns nil by default and results in a panic.

3 participants