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

♻️Refactor: remove redundant field method in DefaultCtx #3372

Merged
merged 2 commits into from
Mar 26, 2025

Conversation

ksw2000
Copy link
Member

@ksw2000 ksw2000 commented Mar 25, 2025

Description

  • Remove the method field in DefaultCtx, which reduces the size of defaultCtx by 16 bytes.
  • The method field can be maintained by methodInt, and the real string can be fetched from app.config.RequestMethods.

Changes introduced

  • Remove method field in defaultCtx
  • Rename methodINT to methodInt due to aligning the function app.methodInt
  • Add new iota variables to represent the method
  • Add app.method() which converts the methodInt to method string

Type of change

  • Performance improvement (non-breaking change which improves efficiency)
  • Code consistency (non-breaking change which improves code reliability and robustness)

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.

Copy link
Contributor

coderabbitai bot commented Mar 25, 2025

Walkthrough

The changes refactor how HTTP methods are represented and processed. A new constant block using iota defines method identifiers, and the DefaultMethods variable is updated from a slice of strings to a map that links these identifiers to method names. In addition, the HTTP method handling in the context (ctx.go) and router (router.go) files is adjusted by renaming fields (from methodINT to methodInt) and updating method access patterns. The helper functions in helpers.go are modified to leverage the new constants and reduce code redundancy.

Changes

File(s) Change Summary
app.go, helpers.go Introduced HTTP method constants using iota; updated method representation from string slice to map[int]string and refined method resolution using constants.
ctx.go, router.go Refactored HTTP method handling by removing a redundant string field, renaming methodINT to methodInt, and updating function calls to use the new method mapping.
ctx_interface.go, ctx_interface_gen.go Renamed method getMethodINT() to getMethodInt() for consistency in naming conventions.

Sequence Diagram(s)

sequenceDiagram
  participant Req as HTTP Request
  participant Ctx as DefaultCtx
  participant App as App
  
  Req->>Ctx: Request with HTTP method header
  Ctx->>Ctx: Reset() sets methodInt from header
  Ctx->>App: Call method(c.methodInt) to resolve method name
  App-->>Ctx: Return corresponding HTTP method string
  Ctx->>Router: Pass method via Route()/next() for further processing
Loading

Poem

I hopped through lines of code so bright,
Changing strings to numbers with delight.
With constants crisp and code so neat,
My little paws make the changes complete.
A joyful rabbit hops in the code garden today! 🐰


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4bf2929 and e01ca4e.

📒 Files selected for processing (6)
  • app.go (1 hunks)
  • ctx.go (5 hunks)
  • ctx_interface.go (1 hunks)
  • ctx_interface_gen.go (1 hunks)
  • helpers.go (4 hunks)
  • router.go (4 hunks)

🪧 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 resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @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 Mar 25, 2025

Codecov Report

Attention: Patch coverage is 96.66667% with 1 line in your changes missing coverage. Please review.

Project coverage is 83.63%. Comparing base (4bf2929) to head (e01ca4e).
Report is 2 commits behind head on main.

Files with missing lines Patch % Lines
helpers.go 92.85% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #3372      +/-   ##
==========================================
- Coverage   83.67%   83.63%   -0.04%     
==========================================
  Files         118      118              
  Lines       11721    11716       -5     
==========================================
- Hits         9807     9799       -8     
- Misses       1486     1488       +2     
- Partials      428      429       +1     
Flag Coverage Δ
unittests 83.63% <96.66%> (-0.04%) ⬇️

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.

@ksw2000 ksw2000 marked this pull request as ready for review March 25, 2025 16:40
@ksw2000 ksw2000 requested a review from a team as a code owner March 25, 2025 16:40
@ksw2000 ksw2000 requested review from gaby, sixcolors, ReneWerner87 and efectn and removed request for a team March 25, 2025 16:40
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)
ctx.go (1)

1950-1952: Renamed method for consistency.

The getter function has been correctly updated to return the renamed methodInt field. The function name getMethodINT() itself still uses the old capitalization pattern - this could potentially be renamed in a future PR for complete consistency.

Consider renaming this method to getMethodInt() in a future PR to maintain complete naming consistency with the field it returns.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4bf2929 and daf0fdb.

📒 Files selected for processing (4)
  • app.go (1 hunks)
  • ctx.go (5 hunks)
  • helpers.go (2 hunks)
  • router.go (3 hunks)
🧰 Additional context used
🧬 Code Definitions (3)
helpers.go (2)
app.go (25)
  • methodGet (460-460)
  • methodHead (461-461)
  • methodPost (462-462)
  • methodPut (463-463)
  • methodDelete (464-464)
  • methodConnect (465-465)
  • methodOptions (466-466)
  • methodTrace (467-467)
  • methodPatch (468-468)
  • app (609-625)
  • app (629-635)
  • app (638-640)
  • app (644-646)
  • app (649-654)
  • app (657-680)
  • app (683-693)
  • app (696-711)
  • app (734-769)
  • app (773-775)
  • app (779-781)
  • app (785-787)
  • app (791-793)
  • app (796-798)
  • app (802-804)
  • app (808-810)
constants.go (8)
  • MethodHead (6-6)
  • MethodPost (7-7)
  • MethodPut (8-8)
  • MethodDelete (10-10)
  • MethodConnect (11-11)
  • MethodOptions (12-12)
  • MethodTrace (13-13)
  • MethodPatch (9-9)
app.go (1)
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)
ctx.go (3)
ctx_interface.go (4)
  • c (46-46)
  • app (45-55)
  • app (58-67)
  • app (70-73)
helpers.go (9)
  • c (613-618)
  • c (620-628)
  • c (630-636)
  • app (97-102)
  • app (105-147)
  • app (150-191)
  • app (543-567)
  • app (653-681)
  • app (683-685)
router.go (7)
  • app (111-157)
  • app (159-212)
  • app (214-243)
  • app (245-274)
  • app (276-295)
  • app (321-396)
  • app (398-432)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Compare
🔇 Additional comments (15)
helpers.go (4)

17-17: Good addition of the slices package for more efficient slice operations.

This change allows for using slices.Index instead of manual iteration when working with slices, which is more efficient and concise.


658-675: Great refactoring using the new constants for method mapping.

The switch statement now uses the named constants (methodGet, methodHead, etc.) instead of hardcoded integer values, making the code more maintainable and self-documenting. This aligns with the PR objective of removing the redundant method field and using methodInt consistently.


680-680: Good simplification using slices.Index for custom method lookup.

Using slices.Index from the standard library to find the index of a method is cleaner and more efficient than manually iterating through the slice.


683-685: Good addition of the method function to complement methodInt.

This new function provides the reverse mapping from methodInt back to the string representation, ensuring that we maintain the functionality while removing the redundant method field from DefaultCtx.

router.go (4)

161-161: Updated field name for consistency.

Renamed from methodINT to methodInt, aligning with the PR objective to use consistent naming for method-related fields.


163-163: Updated field name for consistency.

Renamed from methodINT to methodInt to match the naming convention used elsewhere.


205-205: Good use of the Method() function instead of direct field access.

This change uses c.Method() instead of directly accessing the removed c.method field, aligning with the new architecture where method strings are retrieved from methodInt.


224-224: Updated field name for consistency.

Changed from methodINT to methodInt to maintain consistent naming across the codebase.

app.go (2)

459-469: Good use of iota for defining method constants.

The introduction of this constant block with iota provides a clean way to define numeric identifiers for HTTP methods. This is a better approach than using hardcoded integer values throughout the codebase and supports the PR objective of making the method handling more efficient.


473-481: Well-structured mapping of method constants to their string representations.

The DefaultMethods variable now uses the new constants as indices to map to their corresponding string values from the constants.go file. This creates a clear mapping between the integer identifiers and their string representations, which is easier to maintain and reference.

It's worth noting that the DefaultMethods type has effectively changed from a slice to a map-like structure (using slice indices as keys). This is a good design decision that aligns with the PR objective, as it allows for direct lookup of method strings by their integer identifier.

ctx.go (5)

72-72: Field renamed for consistency.

The field has been correctly renamed from methodINT to methodInt, which improves naming consistency and aligns better with the function app.methodInt.


1006-1009: Method() implementation updated to use new app.method() function.

Good optimization by removing the redundant method field and using c.app.method(c.methodInt) to retrieve the HTTP method string from its integer representation.


1011-1019: Update to Method() for override handling.

The logic for method overriding has been properly updated to use the integer representation of methods. The code now correctly:

  1. Converts the override string to its integer equivalent
  2. Performs validation on the methodInt value
  3. Only updates the context's methodInt when valid
  4. Returns the appropriate method string

This implementation maintains the same functionality while being more memory efficient.


1480-1490: Route() method updated to use Method() function.

The implementation now correctly calls c.Method() instead of directly accessing the now-removed method field. This ensures consistency in how the HTTP method is accessed throughout the codebase.


1909-1926: Reset() method updated to directly set methodInt.

The implementation now sets methodInt directly from the HTTP request header using c.app.methodInt(), eliminating the need for the redundant method field. This approach is more efficient and consistent with the PR's objective.

@ksw2000
Copy link
Member Author

ksw2000 commented Mar 25, 2025

Reduce DefaultCtx from 784 bytes to 728 bytes (-56bytes) 7.1% since ef40c04

goos: linux
goarch: amd64
pkg: github.com/gofiber/fiber/v3
cpu: AMD EPYC 9J14 96-Core Processor                
                                             │   old.txt   │               new.txt               │
                                             │   sec/op    │   sec/op     vs base                │
_Ctx_AcquireReleaseFlow/withoutRequestCtx-16   41.35n ± 1%   28.03n ± 1%  -32.21% (p=0.000 n=20)
_Ctx_AcquireReleaseFlow/withRequestCtx-16      527.9n ± 2%   518.1n ± 1%   -1.86% (p=0.005 n=20)
geomean                                        147.7n        120.5n       -18.43%

                                             │   old.txt    │                  new.txt                  │
                                             │     B/op     │     B/op      vs base                     │
_Ctx_AcquireReleaseFlow/withoutRequestCtx-16     3.000 ± 0%     0.000 ± 0%  -100.00% (p=0.000 n=20)
_Ctx_AcquireReleaseFlow/withRequestCtx-16      1.532Ki ± 0%   1.524Ki ± 0%    -0.51% (p=0.000 n=20)
geomean                                          68.61                      ?                       ¹ ²
¹ summaries must be >0 to compute geomean
² ratios must be >0 to compute geomean

                                             │  old.txt   │                 new.txt                 │
                                             │ allocs/op  │ allocs/op   vs base                     │
_Ctx_AcquireReleaseFlow/withoutRequestCtx-16   1.000 ± 0%   0.000 ± 0%  -100.00% (p=0.000 n=20)
_Ctx_AcquireReleaseFlow/withRequestCtx-16      5.000 ± 0%   4.000 ± 0%   -20.00% (p=0.000 n=20)
geomean                                        2.236                    ?                       ¹ ²
¹ summaries must be >0 to compute geomean
² ratios must be >0 to compute geomean

@ReneWerner87
Copy link
Member

Thx, i will check it tomorrow morning

@gaby gaby added this to the v3 milestone Mar 26, 2025
Copy link
Member

@gaby gaby left a comment

Choose a reason for hiding this comment

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

LGTM, I had similar changes in a local branch a while ago.

@ReneWerner87
Copy link
Member

ok for me
image

this test is very important -> for the custom methods -> ✅

@ReneWerner87 ReneWerner87 merged commit e90fe8a into gofiber:main Mar 26, 2025
17 of 18 checks passed
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.

3 participants