Skip to content

Conversation

@gaby
Copy link
Member

@gaby gaby commented Sep 28, 2025

Summary

Adds native support for net/http and fasthttp handlers in Fiber's router, allowing developers to pass http.Handler, http.HandlerFunc, fasthttp.RequestHandler or compatible function types directly to routing methods without manual adaptation:

  • Converts handler parameter types from Handler to any across all router interfaces
  • Adds automatic conversion logic to detect and wrap net/http handlers using the existing adaptor

Fixes #2202

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Sep 28, 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

Adds adapter helpers to convert net/http and fasthttp handler shapes into Fiber handlers, changes router/App/Group/Register/Router APIs to accept generic any handlers normalized at registration, adds tests for mixed handler flows, and updates documentation and examples with compatibility notes.

Changes

Cohort / File(s) Summary
Adapter helpers & tests
adapter.go, adapter_test.go
Add toFiberHandler, wrapHTTPHandler, collectHandlers to adapt Handler, http.HandlerFunc, http.Handler, func(http.ResponseWriter, *http.Request), and fasthttp.RequestHandler into Fiber Handler; add unit tests covering nils, invalid types, adaptation behavior, header/body propagation, and mixed collections.
App surface & tests
app.go, app_test.go
Change App route methods and Add/All to accept any / ...any; registration normalizes handlers via collectHandlers. Add tests verifying registering net/http handlers across HTTP verbs and expected responses.
Group / Register / Router API
group.go, register.go, router.go
Update Group/Register/Router method signatures from Handler/...Handler to any/...any; implementations convert provided args via collectHandlers before mounting/registration.
Routing tests
router_test.go
Add tests exercising mixed Fiber and net/http handlers, middleware ordering across app/group/route chains, RouteChain interactions, and route-tree rebuilding using []any.
Docs & examples
docs/..., docs/extra/faq.md, docs/middleware/adaptor.md, docs/partials/routing/handler.md, docs/whats_new.md, .github/README.md
Update docs/examples to show direct registration of net/http and fasthttp handler shapes, reuse of converted handlers, and add compatibility/performance caution notes.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor Dev as Developer
  participant App as App / Router
  participant Collector as collectHandlers
  participant Wrapper as Fiber Wrapper
  participant FasthttpAdaptor as fasthttpadaptor
  participant HTTP as net/http Handler
  participant Ctx as fiber.Ctx

  Dev->>App: Register route with http.HandlerFunc / http.Handler / fasthttp.RequestHandler
  App->>Collector: collectHandlers(handler any, ...)
  Collector-->>App: []Wrapper

  Ctx->>Wrapper: invoke converted handler on request
  alt converted net/http handler
    Wrapper->>FasthttpAdaptor: adapt request
    FasthttpAdaptor->>HTTP: ServeHTTP(ResponseWriter, *http.Request)
    HTTP-->>FasthttpAdaptor: write headers/body
    FasthttpAdaptor-->>Ctx: propagate response
  else native Fiber handler
    Wrapper->>Ctx: call Fiber handler directly
  end

  Ctx-->>App: complete response
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Suggested reviewers

  • sixcolors
  • efectn
  • ReneWerner87

Poem

I nibble bytes and hop through routes anew,
From net/http burrows to Fiber meadows I flew.
Any-shaped handlers snug and trim,
Adapted at entry, tidy and prim.
Tests pass — I twitch my whiskers, happy and true. 🐇✨

Pre-merge checks and finishing touches

❌ Failed checks (3 warnings)
Check name Status Explanation Resolution
Linked Issues Check ⚠️ Warning The pull request implements native handler adaptation but does not address the core objectives of issue #2202, which focus on defining an interchangeable router interface, exposing router abstraction for contribution packages, and providing mechanisms to register alternative routers while preserving backward compatibility. Either update the pull request to include implementation of the interchangeable router interface and registration mechanism described in issue #2202 or remove the issue linkage if the scope is only to add handler adaptation.
Out of Scope Changes Check ⚠️ Warning The pull request introduces extensive adapter logic, tests, and documentation for net/http and fasthttp handler support that are unrelated to the interchangeable router interface and contribution package registration mechanisms specified in issue #2202. Scope down the changes to only include the specific router abstraction and registration API defined in issue #2202 or update the linked issue to reflect the handler support feature.
Description Check ⚠️ Warning The description does not follow the required repository template: it uses “## Summary” instead of “# Description,” omits the “## Changes introduced” section with detailed bullets, lacks the “Type of change” section, and does not include the checklist or commit formatting guidance. Update the pull request description to match the provided template by replacing “## Summary” with “# Description,” adding the “## Changes introduced” section with detailed items, including the “Type of change” section, and filling out the checklist and commit formatting guidance.
✅ Passed checks (2 passed)
Check name Status Explanation
Title Check ✅ Passed The title clearly summarizes the main change by highlighting the new native support for net/http and fasthttp handlers in Fiber and directly reflects the content of the PR.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.
✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch add-direct-net/http-handler-support

📜 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 8b07b5d and 364180a.

📒 Files selected for processing (1)
  • docs/whats_new.md (3 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/whats_new.md
🪛 LanguageTool
docs/whats_new.md

[uncategorized] ~304-~304: Do not mix variants of the same word (‘adapter’ and ‘adaptor’) within a single text.
Context: ...ibility Fiber now ships with a routing adapter (see adapter.go) that understands nat...

(EN_WORD_COHERENCY)


[uncategorized] ~304-~304: Do not mix variants of the same word (‘adapter’ and ‘adaptor’) within a single text.
Context: ...r now ships with a routing adapter (see adapter.go) that understands native Fiber hand...

(EN_WORD_COHERENCY)


[uncategorized] ~304-~304: Do not mix variants of the same word (‘adapter’ and ‘adaptor’) within a single text.
Context: ...handlers, all typed as any, and the adapter transparently converts supported handle...

(EN_WORD_COHERENCY)


[grammar] ~1629-~1629: There might be a mistake here.
Context: ... compatible function directly to methods such as app.Get, Group, or `RouteCha...

(QB_NEW_EN)


[grammar] ~1630-~1630: There might be a mistake here.
Context: ... RouteChain and Fiber will adapt it at registration time. Manual wrapping throu...

(QB_NEW_EN)


[grammar] ~1631-~1631: There might be a mistake here.
Context: ...ough the adaptor middleware is no longer required for these common cases. :::not...

(QB_NEW_EN)


[grammar] ~1636-~1636: There might be a mistake here.
Context: ...cause of the extra conversion layer. Use them to ease migrations, but prefer Fibe...

(QB_NEW_EN)


[grammar] ~1637-~1637: There might be a mistake here.
Context: ... handlers in performance-critical paths. ::: ```go httpHandler := http.HandlerFu...

(QB_NEW_EN)


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.

@gaby gaby changed the title test: cover adapter conversions and document net/http support 🔥 feat: Support for net/http router Sep 28, 2025
@codecov
Copy link

codecov bot commented Sep 28, 2025

Codecov Report

❌ Patch coverage is 93.85965% with 7 lines in your changes missing coverage. Please review.
✅ Project coverage is 92.02%. Comparing base (697f199) to head (364180a).
⚠️ Report is 3 commits behind head on main.

Files with missing lines Patch % Lines
adapter.go 88.13% 5 Missing and 2 partials ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #3769      +/-   ##
==========================================
+ Coverage   91.73%   92.02%   +0.28%     
==========================================
  Files         113      115       +2     
  Lines       11966    12249     +283     
==========================================
+ Hits        10977    11272     +295     
+ Misses        727      712      -15     
- Partials      262      265       +3     
Flag Coverage Δ
unittests 92.02% <93.85%> (+0.28%) ⬆️

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.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@gaby gaby added this to v3 Sep 28, 2025
@gaby gaby added this to the v3 milestone Sep 28, 2025
@gaby
Copy link
Member Author

gaby commented Sep 28, 2025

/gemini review

@gaby gaby requested a review from Copilot September 28, 2025 17:12
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 native support for net/http handlers in Fiber's router, allowing developers to pass http.Handler, http.HandlerFunc, or compatible function types directly to routing methods without manual adaptation.

  • Converts handler parameter types from Handler to any across all router interfaces
  • Adds automatic conversion logic to detect and wrap net/http handlers using the existing adaptor
  • Updates documentation to reflect the new capability and show usage examples

Reviewed Changes

Copilot reviewed 12 out of 12 changed files in this pull request and generated 1 comment.

Show a summary per file
File Description
adapter.go New file containing handler conversion logic and utilities
adapter_test.go Comprehensive tests for the new handler conversion functionality
app.go Updated app-level routing methods to accept any type handlers with conversion
app_test.go Added test demonstrating direct net/http handler registration
group.go Updated group routing methods to support mixed handler types
register.go Updated route chain registration methods for any type handlers
router.go Updated Router interface to accept any type handlers
router_test.go Added comprehensive tests for mixed Fiber/HTTP handler scenarios
docs/whats_new.md Added documentation section about the new net/http handler support
docs/partials/routing/handler.md Updated handler documentation with examples and new signatures
docs/middleware/adaptor.md Updated adaptor docs to mention automatic conversion capability
docs/extra/faq.md Updated FAQ to reference direct handler registration

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 introduces a valuable feature by adding native support for net/http handlers in the Fiber router, which significantly improves interoperability. The implementation is clean, well-structured, and accompanied by thorough tests. I've identified a minor area for improvement to enhance code consistency.

@gaby gaby changed the title 🔥 feat: Support for net/http router 🔥 feat: Native support for net/http handlers in the Fiber router Sep 28, 2025
@gaby gaby changed the title 🔥 feat: Native support for net/http handlers in the Fiber router 🔥 feat: Native support for net/http handlers in the router Sep 28, 2025
@gaby
Copy link
Member Author

gaby commented Sep 28, 2025

Fixing lint and review comments in the next hour

@gaby gaby marked this pull request as ready for review September 28, 2025 22:05
@gaby gaby requested a review from a team as a code owner September 28, 2025 22:05
@gaby
Copy link
Member Author

gaby commented Sep 28, 2025

@codex review

@chatgpt-codex-connector
Copy link

Codex Review: Didn't find any major issues. Nice work!

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting

@gaby gaby changed the title 🔥 feat: Native support for net/http handlers in the router 🔥 feat: Native support for net/http handlers Sep 29, 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 (4)
adapter.go (2)

10-15: Broaden GenericHandler and toFiberHandler to include http.Handler for symmetry.

Small completeness tweak: add http.Handler to the constraint and handle it in toFiberHandler so all supported shapes go through one path.

 // GenericHandler enumerates the handler shapes that can be bridged to Fiber.
 type GenericHandler interface {
-	Handler |
-		http.HandlerFunc |
-		func(http.ResponseWriter, *http.Request)
+	Handler |
+		http.Handler |
+		http.HandlerFunc |
+		func(http.ResponseWriter, *http.Request)
 }
 
 // toFiberHandler converts supported handler types to a Fiber handler.
 func toFiberHandler[T GenericHandler](handler T) Handler {
 	switch h := any(handler).(type) {
 	case Handler:
 		return h
+	case http.Handler:
+		return wrapHTTPHandler(h)
 	case http.HandlerFunc:
 		return wrapHTTPHandler(h)
 	case func(http.ResponseWriter, *http.Request):
 		return wrapHTTPHandler(http.HandlerFunc(h))
 	default:
 		return nil
 	}
 }

Also applies to: 17-29


45-60: Polish panic message and avoid ambiguous 'context' param name.

  • Drop trailing newline in panic.
  • Rename parameter to avoid shadowing common package names and improve clarity.
-// collectHandlers converts a slice of handler arguments to Fiber handlers.
-// The context string is used to provide informative panic messages when an
+// collectHandlers converts a slice of handler arguments to Fiber handlers.
+// The where string is used to provide informative panic messages when an
 // unsupported handler type is encountered.
-func collectHandlers(context string, args ...any) []Handler {
+func collectHandlers(where string, args ...any) []Handler {
 	handlers := make([]Handler, 0, len(args))
 
 	for _, arg := range args {
 		handler, ok := convertHandler(arg)
 		if !ok {
-			panic(fmt.Sprintf("%s: invalid handler %T\n", context, arg))
+			panic(fmt.Sprintf("%s: invalid handler %T", where, arg))
 		}
 		handlers = append(handlers, handler)
 	}
 
 	return handlers
 }

Also applies to: 54-55

group.go (1)

85-90: Unify panic message (no trailing newline, use %T).

Minor cleanup for consistency and clearer type reporting.

-			handler, ok := convertHandler(arg)
-			if !ok {
-				panic(fmt.Sprintf("use: invalid handler %v\n", reflect.TypeOf(arg)))
-			}
+			handler, ok := convertHandler(arg)
+			if !ok {
+				panic(fmt.Sprintf("use: invalid handler %T", arg))
+			}
 			handlers = append(handlers, handler)
app.go (1)

805-809: Unify panic message (no trailing newline, use %T).

Mirror the group.Use() cleanup for consistency.

-			handler, ok := convertHandler(arg)
-			if !ok {
-				panic(fmt.Sprintf("use: invalid handler %v\n", reflect.TypeOf(arg)))
-			}
+			handler, ok := convertHandler(arg)
+			if !ok {
+				panic(fmt.Sprintf("use: invalid handler %T", arg))
+			}
 			handlers = append(handlers, handler)
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 606a634 and c5ee81e.

📒 Files selected for processing (4)
  • adapter.go (1 hunks)
  • adapter_test.go (1 hunks)
  • app.go (2 hunks)
  • group.go (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • adapter_test.go
🧰 Additional context used
📓 Path-based instructions (1)
**/*.go

📄 CodeRabbit inference engine (AGENTS.md)

**/*.go: Format Go code using gofumpt (enforced via make format)
Ensure code passes golangci-lint checks (enforced via make lint)
Optimize struct field alignment using betteralign (enforced via make betteralign)
Modernize Go code using gopls modernize (enforced via make modernize)

Files:

  • adapter.go
  • app.go
  • group.go
🧠 Learnings (1)
📚 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:

  • adapter.go
🧬 Code graph analysis (3)
adapter.go (2)
app.go (1)
  • Handler (40-40)
ctx_interface_gen.go (1)
  • Ctx (18-426)
app.go (3)
router.go (2)
  • App (366-385)
  • Router (18-40)
constants.go (9)
  • MethodGet (5-5)
  • MethodHead (6-6)
  • MethodPost (7-7)
  • MethodPut (8-8)
  • MethodDelete (10-10)
  • MethodConnect (11-11)
  • MethodOptions (12-12)
  • MethodTrace (13-13)
  • MethodPatch (9-9)
group.go (1)
  • Group (14-21)
group.go (1)
router.go (1)
  • Router (18-40)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: repeated
  • GitHub Check: Compare
🔇 Additional comments (7)
adapter.go (1)

31-43: LGTM: correct use of fasthttp adaptor and RequestCtx.

The wrapper is concise and uses c.RequestCtx() per prior guidance. Based on learnings

group.go (3)

115-117: API now accepts 'any' for handlers — ensure misuse is covered by tests and docs.

Broader types improve interop but allow invalid values to compile and panic at registration. Confirm docs call this out and tests cover bad types and typed-nil cases.

Also applies to: 121-123, 127-129, 133-135, 139-140, 145-146, 151-152, 156-158, 162-164, 178-181


167-170: LGTM: centralized normalization with collectHandlers in Add.

Good consolidation; simplifies future handler-shape growth.


187-192: LGTM: Group middleware normalization via collectHandlers.

Keeps group behavior consistent with app-level registration.

app.go (3)

831-833: Widened handler parameters to 'any' — confirm docs and tests for misuse and typed-nil.

Same note as group.go: ensure guidance and tests exist for invalid types and nil handlers.

Also applies to: 837-839, 843-845, 849-851, 855-856, 861-862, 867-868, 873-874, 879-880, 891-893


883-886: LGTM: centralized normalization via collectHandlers in Add.

Registration path is clean and consistent.


900-904: LGTM: Group uses collectHandlers for middleware normalization.

Consistent with group.go.

Copy link
Member

@grivera64 grivera64 left a comment

Choose a reason for hiding this comment

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

Aside from a test-related comment, LGTM! 🚀

…dlers. Add support for fasthttp.RequestHandler
@gaby gaby requested a review from Copilot October 12, 2025 04:51
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

Copilot reviewed 13 out of 13 changed files in this pull request and generated 2 comments.

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

284-284: Remove unnecessary loop variable copy.

In Go 1.22+, loop variables are automatically scoped per iteration, making the tt := tt copy unnecessary. You can safely remove this line.

Apply this diff:

 	for _, tt := range tests {
-		tt := tt
 		t.Run(tt.name, func(t *testing.T) {
adapter_test.go (1)

148-148: Remove unnecessary loop variable copy.

In Go 1.22+, loop variables are automatically scoped per iteration, making the tt := tt copy unnecessary.

Apply this diff:

 	for _, tt := range tests {
-		tt := tt
 		t.Run(tt.name, func(t *testing.T) {
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7007cfa and 4c66e25.

📒 Files selected for processing (3)
  • adapter.go (1 hunks)
  • adapter_test.go (1 hunks)
  • app_test.go (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.go

📄 CodeRabbit inference engine (AGENTS.md)

**/*.go: Format Go code using gofumpt (enforced via make format)
Ensure code passes golangci-lint checks (enforced via make lint)
Optimize struct field alignment using betteralign (enforced via make betteralign)
Modernize Go code using gopls modernize (enforced via make modernize)

Files:

  • adapter.go
  • adapter_test.go
  • app_test.go
🧠 Learnings (1)
📚 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:

  • adapter.go
🧬 Code graph analysis (3)
adapter.go (2)
app.go (1)
  • Handler (40-40)
ctx_interface_gen.go (1)
  • Ctx (18-426)
adapter_test.go (3)
app.go (2)
  • Handler (40-40)
  • New (515-628)
ctx_interface_gen.go (1)
  • Ctx (18-426)
constants.go (3)
  • StatusAccepted (54-54)
  • StatusTeapot (91-91)
  • StatusNoContent (56-56)
app_test.go (1)
app.go (2)
  • App (68-110)
  • New (515-628)
🪛 GitHub Actions: golangci-lint
adapter_test.go

[error] 129-129: fieldalignment: struct with 32 pointer bytes could be 24 (govet)

🪛 GitHub Check: lint
adapter_test.go

[failure] 148-148:
The copy of the 'for' variable "tt" can be deleted (Go 1.22+) (copyloopvar)


[failure] 129-129:
fieldalignment: struct with 32 pointer bytes could be 24 (govet)

app_test.go

[failure] 284-284:
The copy of the 'for' variable "tt" can be deleted (Go 1.22+) (copyloopvar)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: unit (1.25.x, windows-latest)
  • GitHub Check: repeated
  • GitHub Check: Compare
🔇 Additional comments (7)
adapter.go (4)

39-46: LGTM!

The fasthttp.RequestHandler conversion is well-implemented. The nil check and the use of c.RequestCtx() align with the framework's patterns for accessing the underlying fasthttp context.

Based on learnings


52-64: LGTM!

The HTTP-to-Fiber adapter is correctly implemented. The use of fasthttpadaptor.NewFastHTTPHandler and c.RequestCtx() follows the framework's established patterns for bridging net/http handlers.

Based on learnings


66-81: LGTM!

The handler collection logic is well-implemented with clear, contextual error messages that include both the handler index and type information, making debugging easier for developers.


83-91: LGTM!

The nil handling and delegation pattern is clean and appropriate for this normalizer function.

app_test.go (1)

201-323: LGTM! Comprehensive test coverage for net/http handler registration.

The test effectively validates that net/http handlers can be registered via all HTTP method routing functions. The special handling for Connect requests (setting scheme/host) and the HEAD method (no body expectation) demonstrates thorough testing.

adapter_test.go (2)

14-236: LGTM! Comprehensive test coverage for adapter functions.

The tests thoroughly cover various conversion scenarios including nil handling, type conversions, mixed handlers, and panic cases. The use of t.Cleanup for resource management and parallel test execution are good practices.


129-145: Address fieldalignment linter issue.

The pipeline is failing due to a fieldalignment issue on the test struct. While this appears to be a false positive (the struct only has 2 fields and reordering won't help), you can add a nolint directive to suppress the warning.

Apply this diff:

+	//nolint:govet // fieldalignment: false positive - struct has only 2 fields
 	tests := []struct {
 		name    string
 		handler any

Alternatively, verify if there's a way to satisfy the linter by restructuring the test data.

@gaby
Copy link
Member Author

gaby commented Oct 12, 2025

/gemini review

@gaby gaby changed the title 🔥 feat: Native support for net/http handlers 🔥 feat: Native support for net/http and fasthttp handlers Oct 12, 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 introduces a great new feature by adding native support for net/http handlers in Fiber. The implementation is solid, with the core conversion logic well-encapsulated in the new adapter.go file. The changes are consistently applied across the router, group, and registration interfaces, and the new functionality is well-tested, including important edge cases. The documentation updates are also thorough and clearly explain the new feature to users. I have a couple of suggestions to further improve the code and documentation.

Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@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

🧹 Nitpick comments (2)
app_test.go (2)

283-322: LGTM! Test execution is sound with correct HTTP semantics.

The test correctly:

  • Creates net/http handlers and registers them via Fiber's routing methods
  • Handles HEAD requests (no body write) and CONNECT requests (URL scheme/host) appropriately
  • Verifies status code, headers, and body content

Optional: Consider using require.NoError for faster test failure.

On line 296, using require.NoError(t, err) instead of assert.NoError(t, err) would cause the test to fail immediately if the write fails, providing clearer error messages rather than continuing with a corrupted response.

Apply this diff:

-				_, err := w.Write([]byte("hello from net/http " + r.Method))
-				assert.NoError(t, err)
+				_, err := w.Write([]byte("hello from net/http " + r.Method))
+				require.NoError(t, err)

218-224: Optional: Make expectBody explicit for HEAD case.

While the current code is correct (omitted expectBody defaults to false), explicitly setting expectBody: false would improve clarity and make the test case's intent more obvious.

Apply this diff:

 		{
 			name: "Head",
 			register: func(app *App, path string, handler any) {
 				app.Head(path, handler)
 			},
-			method: http.MethodHead,
+			method:     http.MethodHead,
+			expectBody: false,
 		},
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 4c66e25 and 57a2e0b.

📒 Files selected for processing (2)
  • adapter_test.go (1 hunks)
  • app_test.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • adapter_test.go
🧰 Additional context used
📓 Path-based instructions (1)
**/*.go

📄 CodeRabbit inference engine (AGENTS.md)

**/*.go: Format Go code using gofumpt (enforced via make format)
Ensure code passes golangci-lint checks (enforced via make lint)
Optimize struct field alignment using betteralign (enforced via make betteralign)
Modernize Go code using gopls modernize (enforced via make modernize)

Files:

  • app_test.go
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (4)
  • GitHub Check: Compare
  • GitHub Check: unit (1.25.x, macos-13)
  • GitHub Check: unit (1.25.x, windows-latest)
  • GitHub Check: repeated
🔇 Additional comments (1)
app_test.go (1)

201-281: LGTM! Comprehensive test coverage for all HTTP methods.

The table-driven test structure is well-designed and covers all standard HTTP methods (GET, HEAD, POST, PUT, DELETE, CONNECT, OPTIONS, TRACE, PATCH). The expectBody flag appropriately distinguishes HEAD requests from others, and the register functions correctly adapt each method for testing.

@gaby
Copy link
Member Author

gaby commented Oct 12, 2025

/gemini review

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 introduces a significant feature: native support for net/http and fasthttp handlers in Fiber's router. The changes are extensive, modifying router interfaces across app, group, and register to accept any type for handlers, and introducing a new adapter.go file with the core conversion logic. The implementation is robust, with comprehensive test coverage for various handler types and edge cases, including typed and untyped nils. The documentation has also been thoroughly updated to reflect these new capabilities and their performance implications. My review includes a suggestion to refactor the handler collection logic for improved clarity and maintainability by centralizing nil checks.

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

69-92: Consider simplifying the nil handling.

The explicit case nil in the switch statement is redundant since toFiberHandler already handles nil by returning (nil, false). While the current implementation is correct and explicit, it could be simplified for consistency.

You can simplify by removing the switch statement entirely:

 func collectHandlers(context string, args ...any) []Handler {
 	handlers := make([]Handler, 0, len(args))
 
 	for i, arg := range args {
-		var (
-			handler Handler
-			ok      bool
-		)
-
-		switch h := arg.(type) {
-		case nil:
-			handler, ok = nil, false
-		default:
-			handler, ok = toFiberHandler(h)
-		}
+		handler, ok := toFiberHandler(arg)
 
 		if !ok {
 			panic(fmt.Sprintf("%s: invalid handler #%d (%T)\n", context, i, arg))
 		}
 		handlers = append(handlers, handler)
 	}
 
 	return handlers
 }

This centralizes all type checking in toFiberHandler, making the code more maintainable. However, the current explicit approach is also clear, so this is optional.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e08a6d5 and 1a7644a.

📒 Files selected for processing (8)
  • .github/README.md (1 hunks)
  • adapter.go (1 hunks)
  • adapter_test.go (1 hunks)
  • app.go (2 hunks)
  • docs/extra/faq.md (1 hunks)
  • docs/partials/routing/handler.md (1 hunks)
  • docs/whats_new.md (2 hunks)
  • group.go (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • docs/extra/faq.md
  • docs/whats_new.md
  • docs/partials/routing/handler.md
🧰 Additional context used
📓 Path-based instructions (1)
**/*.go

📄 CodeRabbit inference engine (AGENTS.md)

**/*.go: Format Go code using gofumpt (enforced via make format)
Ensure code passes golangci-lint checks (enforced via make lint)
Optimize struct field alignment using betteralign (enforced via make betteralign)
Modernize Go code using gopls modernize (enforced via make modernize)

Files:

  • adapter.go
  • group.go
  • adapter_test.go
  • app.go
🧠 Learnings (1)
📚 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:

  • adapter.go
  • .github/README.md
🧬 Code graph analysis (4)
adapter.go (2)
app.go (1)
  • Handler (40-40)
ctx_interface_gen.go (1)
  • Ctx (18-426)
group.go (1)
router.go (1)
  • Router (18-40)
adapter_test.go (2)
app.go (2)
  • Handler (40-40)
  • New (515-628)
ctx_interface_gen.go (1)
  • Ctx (18-426)
app.go (2)
router.go (2)
  • App (366-385)
  • Router (18-40)
group.go (1)
  • Group (14-21)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: Compare
  • GitHub Check: repeated
  • GitHub Check: unit (1.25.x, windows-latest)
🔇 Additional comments (10)
.github/README.md (1)

128-128: LGTM! Clear and accurate description of the new capability.

The updated wording accurately reflects the dual approach: automatic adaptation for common handler shapes at registration time, while preserving the adaptor middleware for more complex scenarios.

adapter_test.go (1)

14-244: LGTM! Comprehensive test coverage for adapter functionality.

The test suite thoroughly covers:

  • Nil handling (typed and untyped)
  • Fiber handler preservation without wrapping
  • HTTP handler shape conversions (http.HandlerFunc, http.Handler, raw function)
  • Fasthttp handler support
  • Mixed handler collections
  • Invalid type panics with clear error messages
  • Resource management via t.Cleanup

All tests properly verify the conversion behavior and maintain parallelism for performance.

adapter.go (2)

13-50: LGTM! Comprehensive handler conversion with proper nil handling.

The function correctly handles all common handler shapes and properly rejects nil values (both typed and untyped) by returning (nil, false), which allows collectHandlers to panic with a clear error message.

The use of c.RequestCtx() at line 44 is correct for accessing the underlying fasthttp context. Based on learnings.


52-64: LGTM! Proper net/http to Fiber adapter using fasthttpadaptor.

The implementation correctly uses fasthttpadaptor.NewFastHTTPHandler to bridge net/http handlers. The nil guard prevents issues, and the closure pattern properly invokes the adapted handler with the fasthttp context. Based on learnings.

group.go (3)

85-89: LGTM! Consistent handler conversion in Use() method.

The change properly uses toFiberHandler to normalize handler inputs, maintaining consistency with the app-level Use() method. The panic message provides clear context for debugging.


167-169: LGTM! Proper batch handler conversion.

The Add() method correctly uses collectHandlers to normalize all handlers (primary + variadic) before registration. The "group" context string provides clear error context.


187-191: LGTM! Consistent handler conversion in Group() method.

The conditional conversion properly handles the optional middleware case, only calling collectHandlers when handlers are provided.

app.go (3)

805-809: LGTM! Simplified and consistent Use() implementation.

The method correctly uses toFiberHandler in the default case, which handles all supported types including Handler. The redundant type-specific cases mentioned in past reviews have been removed.


883-885: LGTM! Proper handler conversion in Add() method.

The implementation correctly uses collectHandlers to normalize all handlers before registration, maintaining consistency with the group-level Add() method.


899-903: LGTM! Consistent Group() method implementation.

The conditional handler conversion mirrors the pattern in group.go, properly normalizing middleware only when provided.

@gaby gaby moved this to In Progress in v3 Oct 12, 2025
@ReneWerner87 ReneWerner87 merged commit 2c43a0f into main Oct 15, 2025
15 checks passed
@github-project-automation github-project-automation bot moved this from In Progress to Done in v3 Oct 15, 2025
@ReneWerner87 ReneWerner87 deleted the add-direct-net/http-handler-support branch October 15, 2025 06:12
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.

🚀 [v3 Feature]: Interchangeable router with contribution packages

4 participants