Skip to content

♻️ Refactor: Improve Req/Res Benchmarks#3693

Merged
ReneWerner87 merged 3 commits intogofiber:mainfrom
grivera64:refactor/improve-benchmarks
Aug 20, 2025
Merged

♻️ Refactor: Improve Req/Res Benchmarks#3693
ReneWerner87 merged 3 commits intogofiber:mainfrom
grivera64:refactor/improve-benchmarks

Conversation

@grivera64
Copy link
Member

Description

This PR is in continuation of issue #3632, to help improve benchmarks for Req and Res. This overhead is largely from the amount of indirection that occurs when accessing data stored inside of DefaultCtx from inside of a DefaultReq or DefaultRes. This also occurs when some methods require both Req and Res methods.

The PR reduces this level of indirection by accessing data directly from DefaultCtx or DefaultReq/DefaultRes.

e.g.

  • r.c.Method() -> r.c.DefaultReq.Method()
  • r.Method() -> r.c.member
  • etc...

Fixes #3632

Changes introduced

  • Benchmarks: Refactors the Req and Res methods to reduce unnecessary function call overhead when not using the Req or Res interfaces.

Type of change

  • Enhancement (improvement to existing features and functionality)
  • Performance improvement (non-breaking change which improves efficiency)

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.

Copilot AI review requested due to automatic review settings August 20, 2025 03:03
@grivera64 grivera64 requested a review from a team as a code owner August 20, 2025 03:03
@coderabbitai
Copy link
Contributor

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

Removed two private helper methods from DefaultCtx and deleted their corresponding Ctx interface declarations. Refactored DefaultReq and DefaultRes internals to access fasthttp and app state directly via the shared DefaultCtx (r.c) while keeping public signatures unchanged.

Changes

Cohort / File(s) Summary of changes
Request internals
req.go
DefaultReq now reads headers, body, queries, files and other request state directly from r.c.fasthttp and r.c.app (uses r.c.methodInt, r.c.values) instead of wrapper accessors.
Response internals
res.go
DefaultRes now writes headers, status, body, encodings, files and rendering output directly to r.c.fasthttp.Response and uses r.c.app config and helpers instead of wrapper accessors.
Ctx interface removals
ctx_interface_gen.go
Removed interface methods setMethodInt(methodInt int) and keepOriginalPath().
DefaultCtx private helpers cleanup
ctx.go
Deleted private helper methods setMethodInt(methodInt int) and keepOriginalPath(); getters remain.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor Client
  participant Req as DefaultReq
  participant Res as DefaultRes
  participant Ctx as DefaultCtx (r.c)
  participant FH as fasthttp.RequestCtx
  participant App as App (r.c.app)

  rect rgba(230,240,255,0.5)
  note over Req,Ctx: Request handling now uses r.c fields directly
  Client->>Req: send request
  Req->>Ctx: read r.c.fasthttp, r.c.app, r.c.methodInt, r.c.values
  Ctx-->>Req: fasthttp request & app config
  Req->>FH: direct header/query/body ops
  end

  rect rgba(230,255,230,0.5)
  note over Res,Ctx: Response writing now uses r.c fields directly
  Req->>Res: produce response
  Res->>Ctx: access r.c.fasthttp.Response and r.c.app
  Ctx-->>Res: response writer & app config
  Res->>FH: set status/headers/body/write output
  end

  note over Ctx: Removed helpers: setMethodInt(), keepOriginalPath()
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Assessment against linked issues

Objective Addressed Explanation
Refactor DefaultReq/DefaultRes to use c *DefaultCtx for shared access (#3632)
Ensure no additional allocations; restore original allocation count in benchmarks (#3632) Benchmarks / runtime allocation measurements required to confirm; not verifiable from diff alone.

Assessment against linked issues: Out-of-scope changes

Code Change Explanation
Removal of Ctx interface methods setMethodInt, keepOriginalPath (ctx_interface_gen.go) The linked issue focuses on DefaultReq/DefaultRes field/layout to reduce allocations; removing interface methods alters the Ctx surface and is not specified in #3632.

Possibly related PRs

Suggested labels

⚡️ Performance

Suggested reviewers

  • sixcolors
  • ReneWerner87
  • efectn
  • gaby

Poem

I nibbled at fields in a cozy den,
Hid two old helpers and hopped out again.
Req and Res now burrow straight to the core,
Through Ctx tunnels they wander and explore.
May benchmarks smile and allocations mend—thump! 🐰✨

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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.
    • 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.
  • 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 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/Issue comments)

Type @coderabbitai help to get the list of available commands.

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

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • 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 @grivera64, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request refactors the internal implementation of Req (Request) and Res (Response) methods to significantly improve performance by reducing indirection. Previously, these methods often accessed underlying data through multiple function calls to DefaultCtx or other intermediate objects. The changes directly access the fasthttp.RequestCtx and App instance members, eliminating unnecessary function call overhead and leading to better benchmark results for request and response handling.

Highlights

  • Performance Improvement: Reduced function call overhead in Req and Res methods by directly accessing underlying fasthttp.RequestCtx and App instance members, rather than through intermediate helper methods.
  • Code Simplification: Eliminated redundant internal methods like setMethodInt and keepOriginalPath from DefaultCtx and its interface, as direct access to fields makes them obsolete.
  • Direct Data Access: Updated numerous Req and Res methods to directly reference r.c.fasthttp (for fasthttp.RequestCtx), r.c.app (for the App instance), and other DefaultCtx fields, streamlining data retrieval.
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. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

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

Footnotes

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

Copy link
Contributor

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 refactors the Req and Res method implementations to reduce function call overhead and improve performance by accessing data directly from the DefaultCtx struct instead of going through method indirection. The changes eliminate unnecessary function calls by replacing method calls like r.c.Method() with direct member access like r.c.member.

Key changes include:

  • Direct access to fasthttp request/response objects instead of method calls
  • Elimination of wrapper methods that add overhead
  • Direct access to app instance and configuration

Reviewed Changes

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

File Description
res.go Refactored all response methods to access fasthttp.Response and app directly instead of through wrapper methods
req.go Refactored all request methods to access fasthttp.Request and app directly instead of through wrapper methods
ctx_interface_gen.go Removed interface methods that are no longer needed due to direct access pattern
ctx.go Removed implementation of wrapper methods that are no longer used

@codecov
Copy link

codecov bot commented Aug 20, 2025

Codecov Report

❌ Patch coverage is 92.10526% with 9 lines in your changes missing coverage. Please review.
✅ Project coverage is 91.81%. Comparing base (9ed35c9) to head (0beadf5).
⚠️ Report is 3 commits behind head on main.

Files with missing lines Patch % Lines
res.go 91.66% 4 Missing and 1 partial ⚠️
req.go 92.59% 4 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #3693      +/-   ##
==========================================
- Coverage   91.97%   91.81%   -0.16%     
==========================================
  Files         114      114              
  Lines       11504    11500       -4     
==========================================
- Hits        10581    10559      -22     
- Misses        663      681      +18     
  Partials      260      260              
Flag Coverage Δ
unittests 91.81% <92.10%> (-0.16%) ⬇️

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.

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 is a great performance-focused refactoring. The changes consistently remove method call indirections by accessing fields or methods on DefaultCtx directly from DefaultReq and DefaultRes. This is done for various methods related to request and response handling, such as accessing headers, body, app configuration, and request context. The removal of setMethodInt and keepOriginalPath from DefaultCtx and inlining their logic at call sites is also a clean way to achieve this. The changes are correct, well-aligned with the goal of improving benchmark performance, and should have a positive impact. I have reviewed the changes and found no issues.

@gaby gaby added this to v3 Aug 20, 2025
@gaby gaby added this to the v3 milestone Aug 20, 2025
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (1)
res.go (1)

478-478: Potential inconsistency in CBOR method

In the CBOR method, line 478 uses response.SetBodyRaw(raw) while other encoder methods like JSON (line 438) and MsgPack (line 458) also use response.SetBodyRaw(raw). However, I notice there's an inconsistent indentation or alignment that might have been introduced during refactoring.

📜 Review details

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

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 9ed35c9 and 9becb04.

📒 Files selected for processing (4)
  • ctx.go (0 hunks)
  • ctx_interface_gen.go (0 hunks)
  • req.go (29 hunks)
  • res.go (33 hunks)
💤 Files with no reviewable changes (2)
  • ctx_interface_gen.go
  • ctx.go
🧰 Additional context used
🧠 Learnings (4)
📓 Common learnings
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`.
Learnt from: gaby
PR: gofiber/fiber#3193
File: middleware/cache/cache_test.go:897-897
Timestamp: 2024-11-08T04:10:42.990Z
Learning: In the Fiber framework, `Context()` is being renamed to `RequestCtx()`, and `UserContext()` to `Context()` to improve clarity and align with Go's context conventions.
📚 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:

  • res.go
  • req.go
📚 Learning: 2024-09-25T15:57:10.221Z
Learnt from: sixcolors
PR: gofiber/fiber#3016
File: middleware/csrf/csrf_test.go:188-193
Timestamp: 2024-09-25T15:57:10.221Z
Learning: In the Fiber framework tests, using `ctx.Response.Header.Cookie` may not be suitable for parsing cookies from the response header, as it requires a `*Cookie` and fills it rather than returning a string value; thus, manual parsing of the `Set-Cookie` header may be necessary.

Applied to files:

  • res.go
📚 Learning: 2024-10-16T14:00:50.724Z
Learnt from: gaby
PR: gofiber/fiber#3170
File: ctx.go:1825-1826
Timestamp: 2024-10-16T14:00:50.724Z
Learning: In the Fiber framework, the `IsProxyTrusted()` function returns `true` when `TrustProxy` is `false`, maintaining compatibility with version 2 behavior.

Applied to files:

  • req.go
🧬 Code Graph Analysis (2)
res.go (2)
req.go (1)
  • DefaultReq (29-31)
ctx_interface_gen.go (1)
  • Ctx (17-403)
req.go (2)
constants.go (9)
  • HeaderAccept (190-190)
  • HeaderAcceptCharset (191-191)
  • HeaderAcceptEncoding (192-192)
  • HeaderAcceptLanguage (193-193)
  • StatusUnsupportedMediaType (88-88)
  • ErrNotImplemented (149-149)
  • StatusNotImplemented (104-104)
  • StatusRequestedRangeNotSatisfiable (89-89)
  • HeaderContentRange (234-234)
res.go (2)
  • DefaultRes (122-124)
  • Cookie (101-113)
⏰ 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). (5)
  • GitHub Check: unit (1.25.x, macos-latest)
  • GitHub Check: unit (1.25.x, macos-13)
  • GitHub Check: unit (1.25.x, windows-latest)
  • GitHub Check: repeated
  • GitHub Check: Compare
🔇 Additional comments (15)
req.go (7)

35-35: Direct fasthttp access improves performance

These refactors eliminate the intermediate method calls and directly access r.c.fasthttp.Request.Header for header operations, which aligns with the PR objective of reducing function-call overhead in benchmarks.

Also applies to: 41-41, 47-47, 54-54, 61-61


92-92: Good optimization for decompression operations

Creating a single request reference and reusing it throughout the decompression logic reduces repeated field access overhead.


174-176: Direct field access for error responses

The change from method calls to direct r.c.DefaultRes field access is consistent with the refactoring pattern and reduces indirection.


252-253: Efficient local variable usage in Fresh()

Good optimization by storing r.c.app locally to avoid repeated field access in the hot path.


543-546: Method signature handling looks correct

The refactored Method() function properly uses direct field access for r.c.methodInt and r.c.app.method() while maintaining the same public API behavior.

Also applies to: 554-554


580-583: Optimized Params() with local variables

Good performance improvement by caching r.c.app, r.c.Route(), and &r.c.values in local variables to reduce repeated field access in the loop.

Also applies to: 594-594


808-809: Direct DefaultRes field access in Range()

The change to r.c.DefaultRes.Status() and r.c.DefaultRes.Set() is consistent with the overall refactoring pattern to reduce indirection.

res.go (8)

128-128: Consistent direct field access pattern

The changes to return r.c.app and r.c.fasthttp directly eliminate wrapper method overhead, aligning with the PR's performance goals.

Also applies to: 190-193


137-137: Header operations optimized

Direct access to r.c.fasthttp.Response.Header.Peek() removes unnecessary indirection for header retrieval operations.

Also applies to: 408-408


274-274: Response handling improvements

Direct fasthttp Response access for SetCookie and Response() methods reduces function call overhead as intended.

Also applies to: 308-308


324-325: Format() method refactoring aligns with req.go changes

The use of r.c.DefaultReq for Accept header processing and direct fasthttp Response access for Content-Type setting maintains consistency across the refactored codebase.

Also applies to: 342-342, 353-353


368-368: AutoFormat() properly uses DefaultReq

The change to use r.c.DefaultReq.Accepts() is consistent with the req.go refactoring and maintains proper separation of concerns.

Also applies to: 378-378


432-432: Encoder methods optimized

All encoder methods (JSON, MsgPack, CBOR, XML, JSONP) now use direct r.c.app.config access for encoders, reducing indirection.

Also applies to: 452-452, 472-472, 491-491, 514-514


758-758: SendFile optimization with path handling

The changes properly maintain the original path for mutable params and original URL restoration, which is important for correct file serving behavior.

Also applies to: 788-788


965-965: End() method properly uses local context variable

Good optimization by storing r.c.fasthttp in a local variable to avoid repeated field access when writing response and closing connection.

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
req.go (1)

580-596: Critical: compile-time error in Params due to pointer-to-slice usage.

values := &r.c.values makes values a pointer; subsequent len(values) and values[i] are invalid and won’t compile. Use the slice directly.

Apply this diff:

-    app := r.c.app
-    route := r.c.Route()
-    values := &r.c.values
+    app := r.c.app
+    route := r.c.Route()
+    values := r.c.values

No other changes needed: len(values) and values[i] will then compile and behave as intended.

🧹 Nitpick comments (6)
req.go (6)

92-92: Nit: simplify condition in multi-encoding decode path.

The decodesRealized > 0 check is redundant (it’s always true inside the loop after increment). Slightly simplifies read and avoids a branch.

Apply this diff:

-        if i > 0 && decodesRealized > 0 {
+        if i > 0 {
             if i == len(encodings)-1 {
                 tempBody := request.Body()
                 *originalBody = make([]byte, len(tempBody))
                 copy(*originalBody, tempBody)
             }
             request.SetBodyRaw(body)
         }

Also applies to: 118-126


304-309: Avoid allocating an interim map from Header.All(): use VisitAll instead.

Header.All() typically builds an intermediate structure. VisitAll iterates without that overhead.

Apply this diff:

-    app := r.c.app
-    headers := make(map[string][]string)
-    for k, v := range r.c.fasthttp.Request.Header.All() {
-        key := app.getString(k)
-        headers[key] = append(headers[key], app.getString(v))
-    }
+    app := r.c.app
+    headers := make(map[string][]string)
+    r.c.fasthttp.Request.Header.VisitAll(func(k, v []byte) {
+        key := app.getString(k)
+        headers[key] = append(headers[key], app.getString(v))
+    })

346-351: Avoid panic on non-TCP transports when extracting port.

RemoteAddr() may not always be *net.TCPAddr (e.g., Unix sockets). Prefer parsing the string form safely.

Apply this diff:

-    tcpaddr, ok := r.c.fasthttp.RemoteAddr().(*net.TCPAddr)
-    if !ok {
-        panic(errors.New("failed to type-assert to *net.TCPAddr"))
-    }
-    return strconv.Itoa(tcpaddr.Port)
+    hostPort := r.c.fasthttp.RemoteAddr().String()
+    _, port, err := net.SplitHostPort(hostPort)
+    if err != nil {
+        return ""
+    }
+    return port

368-368: Consolidate duplicate IP header scanning logic.

extractIPsFromHeader and extractIPFromHeader implement nearly the same scanning/validation. Factor the scanner into a single helper that can return either the first valid IP or a slice to reduce maintenance and ensure consistent validation/rules.

I can draft a shared zero-allocation scanner helper used by both functions if you want to include it in this PR.

Also applies to: 411-416, 429-429, 463-470


541-555: Grammar nit in comment; logic is correct.

The comment under the invalid override branch has a small grammatical issue.

Apply this diff:

-    // Provided override does not valid HTTP method, no override, return current method
+    // Provided override is not a valid HTTP method; do not override; return current method

628-663: Prefer direct header peeks over scanning all headers in Scheme().

Iterating all headers is unnecessary overhead; check only the known proxy headers in order, trimming at the first comma. Behavior remains unchanged.

Apply this diff:

 func (r *DefaultReq) Scheme() string {
-    ctx := r.c.fasthttp
-    if ctx.IsTLS() {
-        return schemeHTTPS
-    }
-    if !r.IsProxyTrusted() {
-        return schemeHTTP
-    }
-
-    app := r.c.app
-    scheme := schemeHTTP
-    const lenXHeaderName = 12
-    for key, val := range ctx.Request.Header.All() {
-        if len(key) < lenXHeaderName {
-            continue // Neither "X-Forwarded-" nor "X-Url-Scheme"
-        }
-        switch {
-        case bytes.HasPrefix(key, []byte("X-Forwarded-")):
-            if bytes.Equal(key, []byte(HeaderXForwardedProto)) ||
-                bytes.Equal(key, []byte(HeaderXForwardedProtocol)) {
-                v := app.getString(val)
-                commaPos := strings.Index(v, ",")
-                if commaPos != -1 {
-                    scheme = v[:commaPos]
-                } else {
-                    scheme = v
-                }
-            } else if bytes.Equal(key, []byte(HeaderXForwardedSsl)) && bytes.Equal(val, []byte("on")) {
-                scheme = schemeHTTPS
-            }
-
-        case bytes.Equal(key, []byte(HeaderXUrlScheme)):
-            scheme = app.getString(val)
-        }
-    }
-    return scheme
+    ctx := r.c.fasthttp
+    if ctx.IsTLS() {
+        return schemeHTTPS
+    }
+    if !r.IsProxyTrusted() {
+        return schemeHTTP
+    }
+
+    app := r.c.app
+    h := &ctx.Request.Header
+
+    if v := app.getString(h.Peek(HeaderXForwardedProto)); v != "" {
+        if i := strings.IndexByte(v, ','); i != -1 {
+            return v[:i]
+        }
+        return v
+    }
+    if v := app.getString(h.Peek(HeaderXForwardedProtocol)); v != "" {
+        if i := strings.IndexByte(v, ','); i != -1 {
+            return v[:i]
+        }
+        return v
+    }
+    if bytes.Equal(h.Peek(HeaderXForwardedSsl), []byte("on")) {
+        return schemeHTTPS
+    }
+    if v := app.getString(h.Peek(HeaderXUrlScheme)); v != "" {
+        return v
+    }
+    return schemeHTTP
 }
📜 Review details

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

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 9becb04 and 0beadf5.

📒 Files selected for processing (1)
  • req.go (28 hunks)
🧰 Additional context used
🧠 Learnings (3)
📓 Common learnings
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`.
Learnt from: gaby
PR: gofiber/fiber#3193
File: middleware/cache/cache_test.go:897-897
Timestamp: 2024-11-08T04:10:42.990Z
Learning: In the Fiber framework, `Context()` is being renamed to `RequestCtx()`, and `UserContext()` to `Context()` to improve clarity and align with Go's context conventions.
📚 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:

  • req.go
📚 Learning: 2024-10-16T14:00:50.724Z
Learnt from: gaby
PR: gofiber/fiber#3170
File: ctx.go:1825-1826
Timestamp: 2024-10-16T14:00:50.724Z
Learning: In the Fiber framework, the `IsProxyTrusted()` function returns `true` when `TrustProxy` is `false`, maintaining compatibility with version 2 behavior.

Applied to files:

  • req.go
🧬 Code Graph Analysis (1)
req.go (3)
constants.go (9)
  • HeaderAccept (190-190)
  • HeaderAcceptCharset (191-191)
  • HeaderAcceptEncoding (192-192)
  • HeaderAcceptLanguage (193-193)
  • StatusUnsupportedMediaType (88-88)
  • ErrNotImplemented (149-149)
  • StatusNotImplemented (104-104)
  • StatusRequestedRangeNotSatisfiable (89-89)
  • HeaderContentRange (234-234)
res.go (1)
  • DefaultRes (122-124)
router.go (1)
  • Route (42-61)
⏰ 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: Compare
  • GitHub Check: repeated
🔇 Additional comments (8)
req.go (8)

35-35: Good switch to direct header access via fasthttp.PeekAll (less indirection).

This reduces function-call overhead and avoids intermediate allocations. Looks correct across Accepts*, AcceptsCharsets, Encodings, and Languages.

Also applies to: 41-41, 47-47, 54-54, 61-61


144-144: Body decoding refactor is sound and preserves original body.

  • Using a local request := &r.c.fasthttp.Request avoids repeated indirection.
  • On error, signaling with DefaultRes.SendStatus and returning a small error body is acceptable, and the original body is restored when needed.
  • Immutable path handled correctly.

Also applies to: 174-177, 181-183


190-190: RequestCtx() now returns the fasthttp context directly — aligned with v3 direction.

Matches ongoing renames from prior work (Context → RequestCtx). Good.


199-199: Direct Cookie/FormValue reads with app.getString are OK.

Avoids extra allocations while keeping semantics. LGTM.

Also applies to: 221-221


231-231: Fresh() optimization looks good.

Using local references to request header and response avoids wrapper hops; ETag/Last-Modified logic preserved.

Also applies to: 252-254


807-809: Range: correct 416 handling with Content-Range header.

Using DefaultRes to set status and Content-Range is correct per RFC semantics.


882-887: IsProxyTrusted logic matches v2 compatibility.

Returning true when TrustProxy is false and validating loopback/private/link-local first aligns with prior behavior. Good.


919-924: getBody: immutable handling and direct fasthttp body access — LGTM.

Copy on immutable path; otherwise returns the live body buffer. Correct and minimal.

@gaby gaby moved this to In Progress in v3 Aug 20, 2025
@ReneWerner87 ReneWerner87 merged commit ac909e8 into gofiber:main Aug 20, 2025
14 of 16 checks passed
@github-project-automation github-project-automation bot moved this from In Progress to Done in v3 Aug 20, 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.

🧹 [Maintenance]: Refactor DefaultReq and DefaultRes fields

4 participants