Skip to content
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

📚 Doc: Add how to use NewCtxFunc and middleware at the same time #3328

Conversation

JIeJaitt
Copy link
Contributor

@JIeJaitt JIeJaitt commented Feb 25, 2025

Description

Add documentation that tells users how to use both NewCtxFunc and app.Use().

Fixes #3319

Changes introduced

List the new features or adjustments introduced in this pull request. Provide details on benchmarks, documentation updates, changelog entries, and if applicable, the migration guide.

  • Benchmarks: Describe any performance benchmarks and improvements related to the changes.
  • Documentation Update: Detail the updates made to the documentation and links to the changed files.
  • Changelog/What's New: Include a summary of the additions for the upcoming release notes.
  • Migration Guide: If necessary, provide a guide or steps for users to migrate their existing code to accommodate these changes.
  • API Alignment with Express: Explain how the changes align with the Express API.
  • API Longevity: Discuss the steps taken to ensure that the new or updated APIs are consistent and not prone to breaking changes.
  • Examples: Provide examples demonstrating the new features or changes in action.

Type of change

Please delete options that are not relevant.

  • Documentation update (changes to documentation)

Checklist

Before you submit your pull request, please make sure you meet these requirements:

  • Followed the inspiration of the Express.js framework for new functionalities, making them similar in usage.
  • Conducted a self-review of the code and provided comments for complex or critical parts.
  • Updated the documentation in the /docs/ directory for Fiber's documentation.
  • Added or updated unit tests to validate the effectiveness of the changes or new features.
  • Ensured that new and existing unit tests pass locally with the changes.
  • Verified that any new dependencies are essential and have been agreed upon by the maintainers/community.
  • Aimed for optimal performance with minimal allocations in the new code.
  • Provided benchmarks for the new code to analyze and improve upon.

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

Copy link
Contributor

coderabbitai bot commented Feb 25, 2025

Walkthrough

A new custom context with enhanced JSON response handling has been introduced. The changes add new structs and methods for response formatting and middleware control flow, as well as corresponding updates in documentation and tests. Additionally, a proxy test now leverages a dynamically created local proxy server for controlled testing. Overall, the modifications improve context management and ensure consistency across middleware execution and route handling.

Changes

File(s) Change Summary
app_test.go Added Response and testCustomCtx structs with new JSON and Next methods; introduced tests (Test_App_CustomCtx_With_Use) verifying JSON responses and middleware logging with/without middleware.
docs/api/app.md Added "Using with Middleware" section; introduced a new CustomCtx type with an overridden Next method; updated main to showcase custom context creation and middleware integration.
middleware/proxy/proxy_test.go Updated the proxy test to use a dynamically created proxy server instead of a hardcoded external URL; adjusted response assertions to expect "mock response" and renamed error variable for consistency.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant CustomCtx
    participant Middleware
    participant RouteHandler

    Client->>CustomCtx: HTTP Request
    CustomCtx->>Middleware: Log context type (before Next)
    Middleware->>CustomCtx: Invoke Next()
    CustomCtx->>RouteHandler: Execute route handler
    RouteHandler-->>CustomCtx: Return response
    CustomCtx->>Middleware: Log context type (after Next)
    CustomCtx-->>Client: Send JSON Response (via Response struct)
Loading

Possibly related PRs

Suggested labels

📒 Documentation, v3

Suggested reviewers

  • gaby
  • sixcolors
  • ReneWerner87
  • efectn

Poem

In the garden of code, I hop with delight,
Custom contexts bloom in the soft moonlight.
JSON responses shine, so clear and neat,
While middleware flows in a rhythmic beat.
With a twitch of my ear, I celebrate tonight!
🐇🌟


📜 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 c85ec75 and e2ad63e.

📒 Files selected for processing (3)
  • app_test.go (1 hunks)
  • docs/api/app.md (1 hunks)
  • middleware/proxy/proxy_test.go (1 hunks)
🔇 Additional comments (5)
middleware/proxy/proxy_test.go (1)

504-521: Great improvement to test reliability and determinism!

Moving from using an external URL (Google) to a local mock server makes this test more reliable, faster, and less prone to network-related failures. The code is also more readable with consistent variable naming (err instead of err1).

docs/api/app.md (1)

559-607: Excellent documentation on preserving custom context types in middleware chains.

This clearly explains a previously undocumented but important pattern for using custom contexts with middleware. The example implementation of Next() properly maintains the context type throughout the request lifecycle by:

  1. Incrementing the handler index
  2. Managing flow between route and application handlers
  3. Ensuring the custom context type is preserved after middleware calls

The documentation addresses issue #3319 effectively with a comprehensive example and clear explanations.

app_test.go (3)

1945-1949: Good addition of a standardized response structure.

This Response struct provides a consistent format for JSON responses, which improves API consistency.


1951-1976: Well-implemented custom context with proper middleware support.

The implementation correctly shows how to:

  1. Extend the DefaultCtx with custom behavior
  2. Override the JSON method to provide a standardized response format
  3. Implement the Next() method to preserve context type throughout middleware execution

This is a good example that exactly matches the documentation in docs/api/app.md.


1978-2041: Comprehensive tests validating custom context behavior.

These tests effectively verify that the custom context works both with and without middleware, ensuring the custom JSON format is correctly applied in both scenarios. The explicit context type logging helps verify that the context type is properly preserved through middleware calls.

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • 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 generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

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. (Beta)
  • @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

codecov bot commented Feb 25, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 84.18%. Comparing base (c85ec75) to head (e2ad63e).
Report is 6 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #3328      +/-   ##
==========================================
- Coverage   84.25%   84.18%   -0.07%     
==========================================
  Files         116      116              
  Lines       11555    11555              
==========================================
- Hits         9736     9728       -8     
- Misses       1391     1397       +6     
- Partials      428      430       +2     
Flag Coverage Δ
unittests 84.18% <ø> (-0.07%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

@JIeJaitt
Copy link
Contributor Author

I didn't change this unit test function but it times out
image

@JIeJaitt JIeJaitt marked this pull request as ready for review February 25, 2025 06:15
@JIeJaitt JIeJaitt requested a review from a team as a code owner February 25, 2025 06:15
@JIeJaitt JIeJaitt requested review from gaby, sixcolors, ReneWerner87 and efectn and removed request for a team February 25, 2025 06:15
@ReneWerner87
Copy link
Member

ReneWerner87 commented Feb 25, 2025

thanks for that, as a user i would expect that this extra effort with the overlays of the next method is not necessary
@efectn Was that the intention?

@JIeJaitt
Copy link
Contributor Author

thanks for that, as a user i would expect that this extra effort with the overlays of the next method is not necessary @efectn what do you say, is that what you want?

This is better, if there is no more discussion I will close this pr.

@efectn
Copy link
Member

efectn commented Feb 25, 2025

thanks for that, as a user i would expect that this extra effort with the overlays of the next method is not necessary @efectn Was that the intention?

I agree with you, i will check it

@JIeJaitt JIeJaitt closed this Feb 27, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

🐛 [Bug]: There is a conflict between app.NewCtxFunc and app.Use
3 participants