Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

🩹 fix: make SetValWithStruct set zero values and support more types #3167 #3227

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

Conversation

ksw2000
Copy link

@ksw2000 ksw2000 commented Dec 2, 2024

Description

According to issue #3167, the SetValWithStruct function originally set only non-zero values, but it also set zero values in slices. After discussion, we have changed the behavior of SetValWithStruct to set both non-zero and zero values, starting from Fiber v3.

Additionally, in this PR, I have made SetValWithStruct more general by supporting more types, including uint, complex, and others.

Since I did not find any statements in the documentation describing that SetValWithStruct about handling zero values, I did not update the documentation. If anyone finds any, I will make the necessary changes.

Fixes #3167

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.

  • Benchmarks: Describe any performance benchmarks and improvements related to the changes.
  • Documentation Update: Detail the updates made to the documentation and links to the changed files.
  • Changelog/What's New: Include a summary of the additions for the upcoming release notes.
  • Migration Guide: If necessary, provide a guide or steps for users to migrate their existing code to accommodate these changes.
  • API Alignment with Express: Explain how the changes align with the Express API.
  • API Longevity: Discuss the steps taken to ensure that the new or updated APIs are consistent and not prone to breaking changes.
  • Examples: Provide examples demonstrating the new features or changes in action.

Type of change

Please delete options that are not relevant.

  • Enhancement (improvement to existing features and functionality)

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.

Commit formatting

Please use emojis in commit messages for an easy way to identify the purpose or intention of a commit. Check out the emoji cheatsheet here: CONTRIBUTING.md

Copy link
Contributor

coderabbitai bot commented Dec 2, 2024

Walkthrough

The changes in this pull request modify the SetValWithStruct function in client/request.go to enhance its ability to handle various data types, including unsigned integers and complex numbers, while allowing zero values to be processed. The associated tests in client/request_test.go have been updated to reflect these changes, adding new fields and adjusting assertions to ensure comprehensive coverage of the updated functionality.

Changes

File Change Summary
client/request.go Updated SetValWithStruct function comment, modified internal logic to handle unsigned integers and complex numbers, refined boolean handling, removed zero value checks, and changed variable name for consistency.
client/request_test.go Expanded args struct with new fields (TUint, TComplex, TFunc, TMap), updated test cases for new fields, removed zero value test, and clarified comments.

Assessment against linked issues

Objective Addressed Explanation
SetValWithStruct should skip 0 in the int slice (Issue #3167) The changes allow zero values to be processed, contrary to the expected behavior.

🐰 In the meadow, I hop and play,
With structs and fields, I find my way.
Zero values now, they come along,
In the world of types, we all belong!
Let's set the values, both big and small,
In this joyful code, we embrace them all! 🌼


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.
    • 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 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.

@ksw2000 ksw2000 marked this pull request as ready for review December 2, 2024 07:04
@ksw2000 ksw2000 requested a review from a team as a code owner December 2, 2024 07:04
@ksw2000 ksw2000 requested review from gaby, sixcolors, ReneWerner87 and efectn and removed request for a team December 2, 2024 07:04
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: 3

🧹 Outside diff range and nitpick comments (1)
client/request_test.go (1)

Line range hint 1468-1515: Exclude unsupported types from benchmark test

The benchmark test includes function and map types, which are not supported for serialization into parameters. Removing these types will make the benchmark more accurate and focused on measuring performance with valid data types.

Apply this diff to modify the benchmark test:

 type args struct { //nolint:govet // Aligning the struct fields is not necessary.
     TString   string
     TSlice    []string
     TIntSlice []int `param:"int_slice"`
     unexport  int
     TInt      int
     TUint     uint
     TFloat    float64
     TComplex  complex128
     TBool     bool
-    TFunc     func()
-    TMap      map[int]int
 }

 b.Run("the struct should be applied", func(b *testing.B) {
     ...
     for i := 0; i < b.N; i++ {
         SetValWithStruct(p, "param", args{
             unexport:  5,
             TInt:      5,
             TUint:     5,
             TString:   "string",
             TFloat:    3.1,
             TComplex:  3 + 4i,
             TBool:     false,
             TSlice:    []string{"foo", "bar"},
             TIntSlice: []int{0, 1, 2},
-            TFunc:     func() {},
-            TMap:      map[int]int{1: 2},
         })
     }
     ...
 })
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 9a2ceb7 and fdbc653.

📒 Files selected for processing (2)
  • client/request.go (4 hunks)
  • client/request_test.go (4 hunks)

Comment on lines +977 to +979
if val.CanInterface() {
p.Add(name, fmt.Sprintf("%#v", val.Interface()))
}
Copy link
Contributor

@coderabbitai coderabbitai bot Dec 2, 2024

Choose a reason for hiding this comment

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

⚠️ Potential issue

Avoid adding unsupported types like functions and maps to parameters

Including function types (func) and map types (map) as parameters may lead to unintended behavior or serialization issues. Functions cannot be serialized, and maps may not serialize in a predictable way suitable for query parameters or form data. Excluding these types will ensure that only supported and serializable types are added.

Apply this diff to exclude functions and maps from being added:

 func SetValWithStruct(p WithStruct, tagName string, v any) {
     ...
     setVal = func(name string, val reflect.Value) {
         switch val.Kind() {
             ...
         default:
+            if val.Kind() == reflect.Func || val.Kind() == reflect.Map {
+                return
+            }
             if val.CanInterface() {
                 p.Add(name, fmt.Sprintf("%#v", val.Interface()))
             }
         }
     }
     ...
 }

Committable suggestion skipped: line range outside the PR's diff.

Copy link
Author

Choose a reason for hiding this comment

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

@ReneWerner87 My design involves writing all types that can be converted into an interface using fmt.Sprintf("%#v", val.Interface()). Do you have any thoughts on this design?

Copy link
Contributor

Choose a reason for hiding this comment

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

Seems like the humans are having a chat. I'll hop back into my burrow for now. If you need me again, just tag @coderabbitai in a new comment, and I'll come hopping out!

Comment on lines +1320 to +1332
// test SetValWithStruct via QueryParam struct.
type args struct { //nolint:govet // Aligning the struct fields is not necessary.
TString string
TSlice []string
TIntSlice []int `param:"int_slice"`
unexport int
TInt int
TUint uint
TFloat float64
TComplex complex128
TFunc func()
TBool bool
TMap map[int]int
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Remove unsupported types from test struct

Including function types (TFunc) and map types (TMap) in the test struct args is not meaningful, as these types are not typically serialized into parameters and may cause serialization issues or unexpected behavior. It is recommended to remove these fields from the test to focus on supported and serializable types.

Apply this diff to remove unsupported types from the test struct:

 type args struct { //nolint:govet // Aligning the struct fields is not necessary.
     TString   string
     TSlice    []string
     TIntSlice []int `param:"int_slice"`
     unexport  int
     TInt      int
     TUint     uint
     TFloat    float64
     TComplex  complex128
-    TFunc     func()
     TBool     bool
-    TMap      map[int]int
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// test SetValWithStruct via QueryParam struct.
type args struct { //nolint:govet // Aligning the struct fields is not necessary.
TString string
TSlice []string
TIntSlice []int `param:"int_slice"`
unexport int
TInt int
TUint uint
TFloat float64
TComplex complex128
TFunc func()
TBool bool
TMap map[int]int
// test SetValWithStruct via QueryParam struct.
type args struct { //nolint:govet // Aligning the struct fields is not necessary.
TString string
TSlice []string
TIntSlice []int `param:"int_slice"`
unexport int
TInt int
TUint uint
TFloat float64
TComplex complex128
TBool bool

Comment on lines +1344 to +1352
TUint: 5,
TString: "string",
TFloat: 3.1,
TComplex: 3 + 4i,
TBool: false,
TSlice: []string{"foo", "bar"},
TIntSlice: []int{1, 2},
TIntSlice: []int{0, 1, 2},
TFunc: func() {},
TMap: map[int]int{1: 2},
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Adjust test cases to reflect supported types only

The test case includes unsupported types like functions and maps. These types should be excluded from the test to prevent misleading results and to focus on verifying the behavior with supported types.

Apply this diff to adjust the test case:

 SetValWithStruct(p, "param", args{
     unexport:  5,
     TInt:      5,
     TUint:     5,
     TString:   "string",
     TFloat:    3.1,
     TComplex:  3 + 4i,
     TBool:     false,
     TSlice:    []string{"foo", "bar"},
     TIntSlice: []int{0, 1, 2},
-    TFunc:     func() {},
-    TMap:      map[int]int{1: 2},
 })
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
TUint: 5,
TString: "string",
TFloat: 3.1,
TComplex: 3 + 4i,
TBool: false,
TSlice: []string{"foo", "bar"},
TIntSlice: []int{1, 2},
TIntSlice: []int{0, 1, 2},
TFunc: func() {},
TMap: map[int]int{1: 2},
TUint: 5,
TString: "string",
TFloat: 3.1,
TComplex: 3 + 4i,
TBool: false,
TSlice: []string{"foo", "bar"},
TIntSlice: []int{0, 1, 2},

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

🧹 Outside diff range and nitpick comments (2)
client/request_test.go (2)

1382-1389: Improve test readability for zero value checks

The zero value test case is buried within multiple similar test blocks. Consider extracting zero value tests into a dedicated test case for better visibility and documentation of the fixed behavior.

+	t.Run("zero values should be set", func(t *testing.T) {
+		t.Parallel()
+		p := &QueryParam{
+			Args: fasthttp.AcquireArgs(),
+		}
+
+		SetValWithStruct(p, "param", args{
+			TInt:      0,
+			TUint:     0,
+			TBool:     false,
+			TIntSlice: []int{0},
+		})
+
+		require.Equal(t, []byte("0"), p.Peek("TInt"))
+		require.Equal(t, []byte("0"), p.Peek("TUint"))
+		require.Equal(t, []byte("false"), p.Peek("TBool"))
+		require.Equal(t, []byte("0"), p.PeekMulti("int_slice")[0])
+	})

Line range hint 1477-1524: Streamline benchmarks to focus on supported types

The benchmark includes unsupported types (TFunc, TMap) which may skew performance metrics. Consider focusing benchmarks on the core supported types to get more accurate performance measurements.

 type args struct {
     TString   string
     TSlice    []string
     TIntSlice []int `param:"int_slice"`
     unexport  int
     TInt      int
     TUint     uint
     TFloat    float64
     TComplex  complex128
     TBool     bool
-    TFunc     func()
-    TMap      map[int]int
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between fdbc653 and 4215e0f.

📒 Files selected for processing (1)
  • client/request_test.go (6 hunks)
🔇 Additional comments (1)
client/request_test.go (1)

1320-1332: Remove unsupported types from test struct

Including function types (TFunc) and map types (TMap) in the test struct args is not meaningful, as these types are not typically serialized into parameters.

@ReneWerner87 ReneWerner87 added the v3 label Dec 2, 2024
@ReneWerner87 ReneWerner87 added this to the v3 milestone Dec 2, 2024
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

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 4215e0f and 5cc62be.

📒 Files selected for processing (1)
  • client/request.go (4 hunks)
🔇 Additional comments (4)
client/request.go (4)

956-957: Support for unsigned integer types added

The addition correctly handles unsigned integer types using strconv.FormatUint, ensuring that uint, uint8, uint16, uint32, uint64, and uintptr are properly converted to strings.


958-959: Support for complex number types added

The inclusion of complex number types (complex64, complex128) and their handling using strconv.FormatComplex is correctly implemented. This allows complex numbers to be added as parameters.


963-964: Boolean false values are now properly handled

The addition of the else branch ensures that when a boolean value is false, it is explicitly added as "false" to the parameters. This change improves the consistency of boolean value handling.


975-977: ⚠️ Potential issue

Avoid adding unsupported types like functions and maps to parameters

Including function types (func) and map types (map) as parameters may lead to unintended behavior or serialization issues. Functions cannot be serialized, and maps may not serialize in a predictable way suitable for query parameters or form data. Excluding these types will ensure that only supported and serializable types are added.

Apply this diff to exclude functions and maps from being added:

 default:
+    if val.Kind() == reflect.Func || val.Kind() == reflect.Map {
+        return
+    }
     if val.CanInterface() {
         p.Add(name, fmt.Sprintf("%#v", val.Interface()))
     }

Comment on lines +933 to +937
// SetValWithStruct sets values using a struct.
// `p` is a structure that implements the WithStruct interface.
// The field name is specified by `tagName`.
// `v` is a struct containing some data.
// Note: This method supports all values that can be converted to an interface.
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Potential misalignment with issue #3167: Zero values are now being set

The changes to SetValWithStruct now cause zero values to be included in parameters. However, the linked issue #3167 specifies that zero values should be skipped consistently across all contexts, including slices. This modification may not align with the expected behavior outlined in the issue. Please revisit the implementation to ensure it meets the desired functionality of skipping zero values.

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

Successfully merging this pull request may close these issues.

🐛 [Bug]: client.SetValWithStruct set zero value if the field is slice
2 participants