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

fix handler order in routing #3321

Open
wants to merge 5 commits into
base: main
Choose a base branch
from

Conversation

ReneWerner87
Copy link
Member

Fixes #3312

@ReneWerner87 ReneWerner87 added this to the v3 milestone Feb 22, 2025
@ReneWerner87 ReneWerner87 requested a review from a team as a code owner February 22, 2025 17:08
@ReneWerner87 ReneWerner87 requested review from gaby, sixcolors and efectn and removed request for a team February 22, 2025 17:08
Copy link
Contributor

coderabbitai bot commented Feb 22, 2025

Walkthrough

This pull request updates the method signatures across several files to replace the middleware ...Handler parameter with a more generic handlers ...Handler parameter. The changes affect the registration of route handlers in the App, Group, Registering, and Router implementations. The internal logic now uses appending methods to properly chain multiple handlers and validates that at least one handler is provided. Additionally, a new test has been added to check the execution order of multiple route handlers.

Changes

File(s) Change Summary
app.go, group.go Updated method signatures across various functions; renamed variadic parameter from middleware to handlers and removed redundant nil arguments in method calls.
register.go Modified All and Add methods to accept a single handler and additional handlers ...Handler, using append to consolidate handler lists.
router.go Updated router interface methods and the register function to use handlers ...Handler instead of separating a single handler and middleware. Added validation to panic if no handler is provided when required.
router_test.go Added a new test function to verify that multiple route handlers execute in the correct order.
docs/api/app.md, docs/partials/routing/handler.md Updated documentation to reflect changes in method signatures, renaming middleware to handlers across various HTTP method handlers.
app_test.go Enhanced error handling in tests by replacing deferred recovery with direct assertions for expected panics.
hooks_test.go Modified error handling in tests to use direct assertions for expected panics instead of deferred recovery.
mount.go Removed nil arguments from register method calls in mount functions for App and Group.

Possibly related PRs

  • 📚 Doc: Update What's New documentation #3181: The changes in the main PR are related to the modifications of method signatures in the App struct and the Group struct, which align with the updates in the router interface mentioned in the retrieved PR, specifically regarding the handling of middleware and handler parameters.
  • 🔥 Feature: Add TestConfig to app.Test() for configurable testing #3161: The changes in the main PR regarding the updates to method signatures and internal logic for handler registration in app.go are related to the modifications in the retrieved PR that also involve updates to the app.Test() method and the introduction of the TestConfig struct, as both PRs focus on enhancing the handling of function parameters and improving the overall structure of the application.
  • 🔥 feat: Improve and Optimize ShutdownWithContext Func #3162: The changes in the main PR, which focus on updating method signatures and internal logic for handler registration in the App struct, are related to the modifications in the retrieved PR that also involve similar updates to method signatures for handler registration in the ShutdownWithContext function and related hooks.

Suggested labels

✏️ Feature, 🧹 Updates

Suggested reviewers

  • gaby
  • sixcolors
  • efectn

Poem

I'm a rabbit hopping in the code,
Skipping through signatures on the road.
Handlers now line up neat and fine,
Middleware woes left behind.
Routes and registers dance in tune,
Celebrating changes 'neath the moon.
Happy hops in Fiber's bloom! 🐇✨


📜 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 4937104 and 3a588a2.

📒 Files selected for processing (4)
  • app_test.go (3 hunks)
  • hooks_test.go (2 hunks)
  • router.go (3 hunks)
  • router_test.go (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • hooks_test.go
  • app_test.go
  • router.go
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: unit (1.23.x, macos-13)
  • GitHub Check: unit (1.23.x, windows-latest)
  • GitHub Check: repeated
  • GitHub Check: Compare
🔇 Additional comments (2)
router_test.go (2)

33-64: Well-structured test for handler execution order!

The test effectively validates that multiple route handlers are executed in the correct sequence, which directly addresses the PR's objective of fixing handler order in routing.


330-344: Good test organization with clear error cases!

The test has been well-refactored into focused sub-tests that clearly validate different error scenarios for missing handlers.

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

🪧 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 22, 2025

Codecov Report

Attention: Patch coverage is 97.53086% with 2 lines in your changes missing coverage. Please review.

Project coverage is 84.15%. Comparing base (283ef32) to head (3a588a2).
Report is 4 commits behind head on main.

Files with missing lines Patch % Lines
register.go 90.90% 2 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #3321      +/-   ##
==========================================
- Coverage   84.15%   84.15%   -0.01%     
==========================================
  Files         116      116              
  Lines       11551    11559       +8     
==========================================
+ Hits         9721     9727       +6     
- Misses       1399     1401       +2     
  Partials      431      431              
Flag Coverage Δ
unittests 84.15% <97.53%> (-0.01%) ⬇️

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.

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 (2)
app.go (1)

753-753: Consider documenting when group is nil.

You're passing nil for the group parameter in app.register. While this looks intentional, adding a brief comment clarifying that nil indicates no group context could improve readability and maintenance.

register.go (1)

48-49: New code for the All method - add test coverage.

Lines 48-49 are newly introduced but flagged by static analysis as uncovered. Consider adding specific test scenarios for the All route usage to ensure coverage.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 48-49: register.go#L48-L49
Added lines #L48 - L49 were not covered by tests

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e5ef561 and 249557c.

📒 Files selected for processing (4)
  • app.go (2 hunks)
  • docs/api/app.md (1 hunks)
  • docs/partials/routing/handler.md (2 hunks)
  • register.go (2 hunks)
🧰 Additional context used
🪛 GitHub Check: codecov/patch
register.go

[warning] 48-49: register.go#L48-L49
Added lines #L48 - L49 were not covered by tests

⏰ Context from checks skipped due to timeout of 90000ms (5)
  • GitHub Check: unit (1.23.x, macos-13)
  • GitHub Check: unit (1.23.x, windows-latest)
  • GitHub Check: repeated
  • GitHub Check: Analyse
  • GitHub Check: Compare
🔇 Additional comments (28)
app.go (11)

759-763: Signature update for Get.

Switching from middleware ...Handler to handlers ...Handler provides a more generic naming scheme. Be sure all references across the codebase and docs are updated accordingly.


767-770: Signature update for Head.

This change aligns with the new handlers ...Handler convention. The method structure appears consistent with the rest of the code.


773-776: Signature update for Post.

Adopting the handlers naming is clear and consistent. No issues found.


779-782: Signature update for Put.

This looks good. The method signature is more descriptive of the parameters involved.


784-787: Signature update for Delete.

No concerns. The parameter change follows the new convention.


788-791: Signature update for Connect.

Consistent naming convention adopted. Code remains clear and straightforward.


794-797: Signature update for Options.

Looks consistent with the updated pattern. No issues spotted.


800-803: Signature update for Trace.

Switching to handlers ...Handler fosters alignment and consistency here as well.


806-809: Signature update for Patch.

Renaming middleware to handlers maintains the uniform naming convention across all methods.


812-815: Signature update for Add.

The revised variadic parameter naming is consistent with the other methods. No additional concerns.


819-821: Signature update for All.

Renaming the parameter for the All method improves clarity and unifies its behavior with other route methods.

register.go (12)

9-19: Renamed interface methods to use 'handlers'.

The interface methods now consistently use handlers ...Handler rather than middleware ...Handler. This uniform terminology reduces confusion about method parameters.


20-20: Signature update for Add in Register interface.

Changing from middleware ...Handler to handlers ...Handler completes the consistency across the interface's methods.


55-56: Signature update for Get.

Renaming to handlers is coherent with the rest of the code. No issues identified.


63-64: Signature update for Head.

All references to middleware replaced by handlers. The code is succinct and consistent.


68-69: Signature update for Post.

Clean transition to the new naming pattern. Looks good.


74-75: Signature update for Put.

No problem spotted. The approach remains consistent.


79-80: Signature update for Delete.

No issues identified. This change aligns with the overall rename effort.


85-86: Signature update for Connect.

Straightforward parameter renaming. The method logic appears unaffected.


91-92: Signature update for Options.

Continues the naming consistency. Good to see the uniform approach maintained.


97-98: Signature update for Trace.

Use of handlers clarifies the function intent. No additional concerns.


103-104: Signature update for Patch.

No issues. This renaming step is consistent with the others.


108-109: Add method usage changed.

Applying handlers ...Handler ensures the function can handle multiple chained handlers seamlessly.

docs/partials/routing/handler.md (4)

12-20: Updated HTTP method signatures to use 'handlers'.

These doc changes accurately reflect the new handlers ...Handler parameter introduced in the code. Documentation remains clear and instructive.


23-23: Add method doc updated.

Renaming the variadic parameter to handlers keeps the documentation consistent with the implementation code.


27-27: All method doc updated.

The revised signature highlights that multiple handlers can be chained, which aligns with the rest of the doc changes.


50-52: Use method doc updated.

Switching from middlewares ...Handler to handlers ...Handler clarifies that any function can be included, whether it's a middleware or a final handler.

docs/api/app.md (1)

137-150: Update variadic parameter naming in Register interface.
The updated documentation correctly reflects the API change where the parameter formerly named middleware ...Handler has been renamed to handlers ...Handler. This change enhances clarity and maintains consistency with the updated routing handler registration logic.

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 (1)
router.go (1)

321-326: Improve the panic message for better debugging.

While the validation for missing handlers is good, the panic message could be more descriptive.

-    panic(fmt.Sprintf("missing handler/middleware in route: %s\n", pathRaw))
+    panic(fmt.Sprintf("missing handler/middleware in route: %s (method: %v)\n", pathRaw, methods))
🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 325-325: router.go#L325
Added line #L325 was not covered by tests

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 249557c and e796099.

📒 Files selected for processing (1)
  • router.go (2 hunks)
🧰 Additional context used
🪛 GitHub Check: codecov/patch
router.go

[warning] 325-325: router.go#L325
Added line #L325 was not covered by tests

⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: unit (1.23.x, macos-13)
  • GitHub Check: unit (1.23.x, macos-latest)
  • GitHub Check: unit (1.23.x, windows-latest)
  • GitHub Check: Compare
  • GitHub Check: repeated
  • GitHub Check: Analyse
🔇 Additional comments (1)
router.go (1)

23-34: LGTM! Consistent parameter naming across Router interface methods.

The change from middleware ...Handler to handlers ...Handler improves code consistency and better reflects that these parameters can be both middleware and regular handlers.

router.go Outdated
Comment on lines 324 to 326
if len(handlers) == 0 && !isMount {
panic(fmt.Sprintf("missing handler/middleware in route: %s\n", pathRaw))
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Verification agent

🧩 Analysis chain

Add test coverage for the missing handler validation.

The static analysis indicates that the validation code is not covered by tests. Please add test cases to verify this validation.


🏁 Script executed:

#!/bin/bash
# Description: Check if there are any existing tests for missing handler validation

echo "Searching for existing tests..."
rg -l 'missing handler/middleware in route' test_*.go || echo "No existing tests found"

echo -e "\nSearching for similar panic tests..."
ast-grep --pattern 'func Test$_($_ *testing.T) {
  $$$
  panic($$$)
  $$$
}'

Length of output: 405


Action Required: Add Tests for Missing Handler Validation

The current code in router.go (lines 324-326) triggers a panic when no handler/middleware is provided:

	if len(handlers) == 0 && !isMount {
		panic(fmt.Sprintf("missing handler/middleware in route: %s\n", pathRaw))
	}

However, our search confirms that there are no tests covering this scenario. Please add test cases that explicitly:

  • Invoke the route setup with an empty handler list.
  • Assert that the function panics with the expected error message.
🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 325-325: router.go#L325
Added line #L325 was not covered by tests

Copy link
Contributor

@github-actions github-actions bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Performance Alert ⚠️

Possible performance regression was detected for benchmark.
Benchmark result of this commit is worse than the previous benchmark result exceeding threshold 1.50.

Benchmark suite Current: 3a588a2 Previous: 4b62d3d Ratio
Benchmark_Compress_Levels/Brotli_LevelBestCompression - B/op 5 B/op 0 B/op +∞
BenchmarkAppendMsgitem-4_middleware_csrf - MB/s 3216.1 MB/s 1606.62 MB/s 2.00
BenchmarkAppendMsgstorageManager - MB/s 3203.76 MB/s 1605.07 MB/s 2.00

This comment was automatically generated by workflow using github-action-benchmark.

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 (1)
router.go (1)

324-324: Consider using string concatenation for better performance.

Replace fmt.Sprintf with string concatenation for better performance in error messages.

-panic(fmt.Sprintf("missing handler/middleware in route: %s", pathRaw))
+panic("missing handler/middleware in route: " + pathRaw)

-panic(fmt.Sprintf("nil handler in route: %s", pathRaw))
+panic("nil handler in route: " + pathRaw)

Also applies to: 329-329

🧰 Tools
🪛 GitHub Check: lint

[failure] 324-324:
fmt.Sprintf can be replaced with string concatenation (perfsprint)

🪛 GitHub Actions: golangci-lint

[warning] 324-324: fmt.Sprintf can be replaced with string concatenation (perfsprint)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e796099 and 4937104.

📒 Files selected for processing (5)
  • app_test.go (3 hunks)
  • hooks_test.go (2 hunks)
  • mount.go (2 hunks)
  • router.go (3 hunks)
  • router_test.go (2 hunks)
🧰 Additional context used
🪛 GitHub Check: lint
router.go

[failure] 324-324:
fmt.Sprintf can be replaced with string concatenation (perfsprint)


[failure] 329-329:
fmt.Sprintf can be replaced with string concatenation (perfsprint)

🪛 GitHub Actions: golangci-lint
router.go

[warning] 324-324: fmt.Sprintf can be replaced with string concatenation (perfsprint)

⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: unit (1.23.x, windows-latest)
  • GitHub Check: Compare
  • GitHub Check: repeated
🔇 Additional comments (9)
hooks_test.go (1)

89-91: LGTM! Enhanced test robustness.

The addition of explicit failure checks when expected panics don't occur improves test reliability by preventing false positives.

Also applies to: 175-177

mount.go (1)

58-58: LGTM! Simplified handler registration.

The removal of the nil argument aligns with the updated handler registration pattern across the codebase.

Also applies to: 88-88

router.go (2)

23-34: LGTM! Consistent handler parameter naming.

The standardization of handlers ...Handler across all router methods improves API consistency.


323-331: LGTM! Added robust handler validation.

The new validation ensures that routes are properly configured with valid handlers, preventing runtime issues.

🧰 Tools
🪛 GitHub Check: lint

[failure] 324-324:
fmt.Sprintf can be replaced with string concatenation (perfsprint)


[failure] 329-329:
fmt.Sprintf can be replaced with string concatenation (perfsprint)

🪛 GitHub Actions: golangci-lint

[warning] 324-324: fmt.Sprintf can be replaced with string concatenation (perfsprint)

router_test.go (2)

34-65: LGTM! Added comprehensive handler order test.

The new test effectively verifies that multiple handlers are executed in the correct sequence.


331-352: LGTM! Improved test organization.

The restructuring into sub-tests for "No Handler" and "Nil Handler" scenarios improves test clarity and maintainability.

app_test.go (3)

485-486: LGTM! Improved test reliability by handling missing panic case.

The addition of the else clause ensures the test fails explicitly when an expected panic doesn't occur, making the test more reliable and easier to debug.


1063-1064: LGTM! Consistent error handling for panic recovery.

The added else clause follows the same pattern as other panic tests, maintaining consistency throughout the test suite.


1295-1296: LGTM! Completed panic recovery with proper error handling.

The else clause addition completes the panic recovery pattern, ensuring test failures are explicit when expected panics don't occur.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
Status: No status
Development

Successfully merging this pull request may close these issues.

🐛 [Bug]: Specifying middleware in the handler doesn't work
1 participant