-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
🧹 chore: Simplify generic function calls #3578
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
Conversation
Thanks for opening this pull request! 🎉 Please check out our contributing guidelines. If you need help or want to chat with us, join us on Discord https://gofiber.io/discord |
WalkthroughThe changes refactor conditional logic in several functions by replacing if-else statements with switch statements for clarity and consistency. Additionally, explicit generic type parameters are removed from function calls in both production and test code, relying on type inference instead. No public APIs or method signatures are altered. Changes
Sequence Diagram(s)sequenceDiagram
participant Client
participant DefaultCtx
participant HeaderParser
Client->>DefaultCtx: extractIPsFromHeader(header)
DefaultCtx->>HeaderParser: loop through header chars (switch on ':' or '.')
HeaderParser-->>DefaultCtx: Return parsed IPs
DefaultCtx-->>Client: Return list of IPs
Possibly related PRs
Suggested labels
Suggested reviewers
Poem
📜 Recent review detailsConfiguration used: CodeRabbit UI 📒 Files selected for processing (2)
🚧 Files skipped from review as they are similar to previous changes (2)
✨ Finishing Touches
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. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. 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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this 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 @axrav, 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 focuses on internal code optimizations to enhance readability, maintainability, and performance. The primary changes involve replacing multi-condition if-else if
chains with switch
statements and simplifying generic function calls by leveraging Go's type inference, particularly within context and state management functionalities and their corresponding tests.
Highlights
- Conditional Logic Refactoring: I've refactored several
if-else if
statements into more efficient and readableswitch
statements. This applies to IP address parsing logic withinctx.go
and route path matching inrouter.go
, aiming for improved performance and code clarity. - Generic Type Simplification: I've simplified generic function calls by removing explicit type parameters where Go's type inference can automatically determine the type. This change is primarily visible in
ctx.go
(forQuery
method calls) and various test files (ctx_test.go
,state_test.go
) for functions likeLocals
andGetState
, making the code cleaner and less verbose.
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 is currently in preview and 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 to provide feedback.
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
-
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. ↩
There was a problem hiding this 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 various generic function calls to leverage type inference and replaces if-else
chains with switch
statements for improved readability and performance.
- Swapped
if-else
chains forswitch
in context and router logic - Simplified generic calls by removing explicit type arguments in tests and code
Reviewed Changes
Copilot reviewed 4 out of 4 changed files in this pull request and generated 2 comments.
File | Description |
---|---|
state_test.go | Removed explicit generic type parameters in runGenericTest and benchmark calls |
ctx_test.go | Simplified calls to Locals and Query by relying on type inference |
ctx.go | Replaced two if-else chains in IP extraction and Query method with switch statements |
router.go | Replaced if/else if route matching with a switch on routePath |
There was a problem hiding this 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)
router.go (1)
642-648
: Switch works, but the two cases still duplicate the same append – consider collapsing themThe new
switch
is clearer than the oldif
chain, but bothcase 0
andcase treePath
execute the very same statement.
A small refactor keeps intent while removing duplication:- switch routePath { - case 0: - tsMap[treePath] = append(tsMap[treePath], route) - case treePath: - tsMap[treePath] = append(tsMap[treePath], route) - } + if routePath == 0 || routePath == treePath { + tsMap[treePath] = append(tsMap[treePath], route) + }Less code, same behavior, no extra allocations.
(If you prefer sticking with aswitch
, keep a singlecase
and usefallthrough
.)state_test.go (1)
908-909
: Minor: make the default value explicitly typed to avoid future surprises
0
is an untyped constant and defaults toint
, which is what you want today.
If someone changes the benchmark to useuint
(or any other numeric type), the call will start inferring the wrongT
silently. To make intention crystal-clear:- GetStateWithDefault(st, key, 0) + GetStateWithDefault[int](st, key, 0)Not critical, just a belt-and-braces suggestion.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (4)
ctx.go
(3 hunks)ctx_test.go
(3 hunks)router.go
(1 hunks)state_test.go
(2 hunks)
🧰 Additional context used
🧠 Learnings (5)
📓 Common learnings
Learnt from: sixcolors
PR: gofiber/fiber#3446
File: docs/middleware/logger.md:44-44
Timestamp: 2025-05-13T00:19:16.407Z
Learning: In documentation files for the Fiber framework, code examples are often partial and don't repeat import statements that were shown in earlier examples, focusing instead on demonstrating specific usage patterns.
Learnt from: ReneWerner87
PR: gofiber/fiber#3161
File: app.go:923-932
Timestamp: 2024-11-15T07:56:21.623Z
Learning: In the Fiber framework, breaking changes are acceptable when moving from version 2 to version 3, including modifications to method signatures such as in the `Test` method in `app.go`.
router.go (2)
Learnt from: ReneWerner87
PR: gofiber/fiber#3161
File: app.go:923-932
Timestamp: 2024-11-15T07:56:21.623Z
Learning: In the Fiber framework, breaking changes are acceptable when moving from version 2 to version 3, including modifications to method signatures such as in the `Test` method in `app.go`.
Learnt from: ckoch786
PR: gofiber/fiber#3230
File: docs/whats_new.md:944-951
Timestamp: 2024-12-15T19:56:45.935Z
Learning: Detailed usage examples and explanations for new methods like `RemoveRoute` and `RemoveRouteByName` are documented in `docs/api/app.md`, so it's unnecessary to duplicate them in `docs/whats_new.md`.
state_test.go (6)
Learnt from: ReneWerner87
PR: gofiber/fiber#3161
File: app.go:923-932
Timestamp: 2024-11-15T07:56:21.623Z
Learning: In the Fiber framework, breaking changes are acceptable when moving from version 2 to version 3, including modifications to method signatures such as in the `Test` method in `app.go`.
Learnt from: efectn
PR: gofiber/fiber#3162
File: hooks_test.go:228-228
Timestamp: 2024-12-13T08:14:22.851Z
Learning: In Go test files, prefer using the `require` methods from the `testify` package for assertions instead of manual comparisons and calls to `t.Fatal` or `t.Fatalf`.
Learnt from: sixcolors
PR: gofiber/fiber#3016
File: middleware/session/store.go:164-167
Timestamp: 2024-10-08T19:06:06.583Z
Learning: Unit tests in this project use testify require.
Learnt from: sixcolors
PR: gofiber/fiber#3016
File: middleware/session/store.go:164-167
Timestamp: 2024-10-02T23:03:31.727Z
Learning: Unit tests in this project use testify require.
Learnt from: sixcolors
PR: gofiber/fiber#2922
File: middleware/cors/utils.go:63-71
Timestamp: 2024-10-08T19:06:06.583Z
Learning: The project uses the testify/assert package for assertions in unit tests.
Learnt from: sixcolors
PR: gofiber/fiber#2922
File: middleware/cors/utils.go:63-71
Timestamp: 2024-07-26T21:00:12.902Z
Learning: The project uses the testify/assert package for assertions in unit tests.
ctx_test.go (13)
undefined
<retrieved_learning>
Learnt from: gaby
PR: #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.
</retrieved_learning>
<retrieved_learning>
Learnt from: ReneWerner87
PR: #3161
File: app.go:923-932
Timestamp: 2024-11-15T07:56:21.623Z
Learning: In the Fiber framework, breaking changes are acceptable when moving from version 2 to version 3, including modifications to method signatures such as in the Test
method in app.go
.
</retrieved_learning>
<retrieved_learning>
Learnt from: gaby
PR: #3170
File: ctx_test.go:1721-1724
Timestamp: 2024-10-16T12:12:30.506Z
Learning: In the Go unit tests in ctx_test.go
, it is acceptable to use invalid CIDR notation such as "0.0.0.1/31junk"
for testing purposes.
</retrieved_learning>
<retrieved_learning>
Learnt from: gaby
PR: #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
.
</retrieved_learning>
<retrieved_learning>
Learnt from: efectn
PR: #3162
File: hooks_test.go:228-228
Timestamp: 2024-12-13T08:14:22.851Z
Learning: In Go test files, prefer using the require
methods from the testify
package for assertions instead of manual comparisons and calls to t.Fatal
or t.Fatalf
.
</retrieved_learning>
<retrieved_learning>
Learnt from: efectn
PR: #3162
File: app_test.go:893-895
Timestamp: 2024-11-29T12:37:27.581Z
Learning: In the Test_App_ShutdownWithContext
function in app_test.go
, the clientDone
channel is used to synchronize the client's request completion before proceeding, eliminating the need for additional time.Sleep
calls.
</retrieved_learning>
<retrieved_learning>
Learnt from: sixcolors
PR: #3016
File: middleware/session/config.go:122-122
Timestamp: 2024-09-25T16:18:34.719Z
Learning: In DefaultErrorHandler(c *fiber.Ctx, err error)
, since c
is a pointer to an interface, we need to dereference *c
when calling interface methods like SendStatus
.
</retrieved_learning>
<retrieved_learning>
Learnt from: sixcolors
PR: #3016
File: middleware/session/config.go:122-122
Timestamp: 2024-10-08T19:06:06.583Z
Learning: In DefaultErrorHandler(c *fiber.Ctx, err error)
, since c
is a pointer to an interface, we need to dereference *c
when calling interface methods like SendStatus
.
</retrieved_learning>
<retrieved_learning>
Learnt from: sixcolors
PR: #3016
File: middleware/session/middleware_test.go:400-407
Timestamp: 2024-09-25T17:09:03.756Z
Learning: In the Test_Session_Next
function in middleware/session/middleware_test.go
, the variable doNext
is properly synchronized with the muNext
mutex for both read and write access.
</retrieved_learning>
<retrieved_learning>
Learnt from: sixcolors
PR: #3016
File: middleware/session/store.go:164-167
Timestamp: 2024-10-02T23:03:31.727Z
Learning: Unit tests in this project use testify require.
</retrieved_learning>
<retrieved_learning>
Learnt from: sixcolors
PR: #3016
File: middleware/session/store.go:164-167
Timestamp: 2024-10-08T19:06:06.583Z
Learning: Unit tests in this project use testify require.
</retrieved_learning>
<retrieved_learning>
Learnt from: sixcolors
PR: #2922
File: middleware/cors/utils.go:63-71
Timestamp: 2024-10-08T19:06:06.583Z
Learning: The project uses the testify/assert package for assertions in unit tests.
</retrieved_learning>
<retrieved_learning>
Learnt from: sixcolors
PR: #2922
File: middleware/cors/utils.go:63-71
Timestamp: 2024-07-26T21:00:12.902Z
Learning: The project uses the testify/assert package for assertions in unit tests.
</retrieved_learning>
ctx.go (3)
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: 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.
Learnt from: sixcolors
PR: gofiber/fiber#3016
File: middleware/csrf/csrf_test.go:188-193
Timestamp: 2024-10-08T19:06:06.583Z
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.
🔇 Additional comments (7)
state_test.go (1)
471-490
: LGTM – implicit type-argument inference is fineDropping the explicit
[T]
fromrunGenericTest
calls improves readability; Go’s type inference infersT
from the slice literal, so this compiles on 1.22+. The explicit type arguments onGetState[...]
remain necessary and are untouched. No issues here.ctx.go (3)
871-876
: LGTM! Switch statement improves readability and performance.The refactoring from if-else to switch statement for character checking is well-implemented. This change improves code clarity when checking for IPv6 (
:
) and IPv4 (.
) indicators in header parsing, and switch statements are generally more efficient for multiple condition checks.
922-927
: LGTM! Consistent switch statement implementation.This switch statement matches the pattern used in
extractIPsFromHeader
and provides the same performance and readability benefits. The logic for detecting IPv6 and IPv4 address formats is preserved and more clearly expressed.
1291-1291
: LGTM! Generic function call simplification works correctly.The removal of explicit generic type parameters from the
Query
function call is appropriate here. Go's type inference will correctly determine thatV
should bestring
based on the method signaturefunc (c *DefaultCtx) Query(key string, defaultValue ...string) string
and the call toQuery[V GenericType](c Ctx, key string, defaultValue ...V) V
. This change improves code readability while maintaining the same functionality.ctx_test.go (3)
2514-2516
: LGTM! Improved code clarity by relying on type inference.The removal of explicit generic type parameters simplifies the function calls while maintaining the same functionality. Go's type inference can correctly determine the types from the values being stored (
"doe"
→ string,18
→ int,true
→ bool).
2542-2542
: LGTM! Simplified generic function call with type inference.The explicit generic type parameter is correctly removed as Go can infer the
User
type from the struct literal value being passed to theLocals
function.
3062-3062
: LGTM! Type inference simplifies the Query function call.The explicit generic type parameter is correctly removed as Go can infer the string type from the default value
"default"
being passed to theQuery
function.
There was a problem hiding this 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 refactors the codebase by replacing if-else
chains with switch
statements and simplifying generic function calls. I've suggested a simplification in router.go
to remove code duplication. Overall, the changes improve code quality.
Codecov ReportAttention: Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## main #3578 +/- ##
=======================================
Coverage 90.96% 90.97%
=======================================
Files 111 111
Lines 11124 11121 -3
=======================================
- Hits 10119 10117 -2
- Misses 753 754 +1
+ Partials 252 250 -2
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
Congrats on merging your first pull request! 🎉 We here at Fiber are proud of you! If you need help or want to chat with us, join us on Discord https://gofiber.io/discord |
Description
Used switch tags instead of if loops, simplified state management in context and tests
Fixes # (issue)
Changes introduced
List the new features or adjustments introduced in this pull request. Provide details on benchmarks, documentation updates, changelog entries, and if applicable, the migration guide.
Type of change
Please delete options that are not relevant.
Checklist
Before you submit your pull request, please make sure you meet these requirements:
/docs/
directory for [Fiber's documentation](https://docs.gofiber.io/).Detailed Changes
1. Switch Statement Optimization
Before:
After:
2. Simplified Generic Type Usage in Tests
Before:
After:
These changes improve code readability and performance by: