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

client: add support for iterator methods #3228

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

Conversation

efectn
Copy link
Member

@efectn efectn commented Dec 2, 2024

Description

  • Simplify parserRequestFile logic using io.Copy
  • Add go1.23 iterator methods for both request and response instance

Todo:

  • Add documentations.

Fixes #3184

Changes introduced

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

Type of change

  • New feature (non-breaking change which adds functionality)

Checklist

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

@efectn efectn requested a review from a team as a code owner December 2, 2024 09:08
@efectn efectn requested review from gaby, sixcolors and ReneWerner87 and removed request for a team December 2, 2024 09:08
Copy link
Contributor

coderabbitai bot commented Dec 2, 2024

Walkthrough

The pull request introduces significant enhancements to the handling of HTTP requests and responses in the client package. Key changes include the implementation of new iterator methods for accessing headers, parameters, cookies, and form data in the Request struct, as well as a new method for retrieving headers in the Response struct. Additionally, the file upload process has been optimized by replacing a fixed-size buffer with a dynamic buffer for improved efficiency. The changes are complemented by an expanded test suite to ensure correctness and performance.

Changes

File Change Summary
client/hooks.go Replaced fixed-size buffer for file uploads with a dynamic 1MB buffer; simplified file reading logic.
client/request.go Added iterator methods: Headers, Params, Cookies, PathParams, FormDatas; added Keys methods for QueryParam and FormData.
client/request_test.go Introduced tests and benchmarks for new request methods; updated existing tests for robustness.
client/response.go Added Headers method to retrieve response headers; updated comments for Cookies method.
client/response_test.go Added Test_Response_Headers and Benchmark_Headers for header handling; minor updates to existing tests.

Assessment against linked issues

Objective Addressed Explanation
Add a straightforward approach for accessing response headers in *fiber.Agent (3184)

Possibly related PRs

Suggested labels

🧹 Updates

Suggested reviewers

  • sixcolors
  • efectn
  • ReneWerner87

Poem

In the land of code where rabbits hop,
New methods bloom, and the changes won't stop.
Headers and params, all easy to find,
With buffers so nimble, oh, how they unwind!
So let’s celebrate with a joyful cheer,
For a smoother code path, we hold so dear! 🐇✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 7578ae3 and 26a3439.

📒 Files selected for processing (1)
  • client/hooks.go (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • client/hooks.go

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.

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: 10

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

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

📒 Files selected for processing (5)
  • client/hooks.go (2 hunks)
  • client/request.go (9 hunks)
  • client/request_test.go (7 hunks)
  • client/response.go (2 hunks)
  • client/response_test.go (2 hunks)
🧰 Additional context used
🪛 golangci-lint (1.62.2)
client/hooks.go

[warning] 276-276: unhandled-error: Unhandled error in call to function io.CopyBuffer

(revive)


276-276: Error return value of io.CopyBuffer is not checked

(errcheck)

client/response_test.go

[warning] 229-229: unhandled-error: Unhandled error in call to function fmt.Print

(revive)


229-229: use of fmt.Print forbidden by pattern ^fmt\.Print(f|ln)?$

(forbidigo)


229-229: Error return value of fmt.Print is not checked

(errcheck)


229-229: unnecessary conversion

(unconvert)


230-230: unnecessary conversion

(unconvert)


[warning] 273-273: empty-block: this block is empty, you can remove it

(revive)

client/request.go

735-735: append to slice keys with non-zero initialized length

(makezero)


875-875: append to slice keys with non-zero initialized length

(makezero)

client/request_test.go

[warning] 190-190: empty-block: this block is empty, you can remove it

(revive)


[warning] 349-349: empty-block: this block is empty, you can remove it

(revive)


[warning] 464-464: empty-block: this block is empty, you can remove it

(revive)


[warning] 574-574: empty-block: this block is empty, you can remove it

(revive)

🪛 GitHub Check: lint
client/hooks.go

[failure] 276-276:
unhandled-error: Unhandled error in call to function io.CopyBuffer (revive)


[failure] 276-276:
Error return value of io.CopyBuffer is not checked (errcheck)

client/request.go

[failure] 734-734:
unused-parameter: parameter 'value' seems to be unused, consider removing or renaming it as _ (revive)


[failure] 735-735:
append to slice keys with non-zero initialized length (makezero)


[failure] 874-874:
unused-parameter: parameter 'value' seems to be unused, consider removing or renaming it as _ (revive)


[failure] 875-875:
append to slice keys with non-zero initialized length (makezero)

🔇 Additional comments (3)
client/request_test.go (1)

8-8: Verify compatibility of the maps package with the project's Go version

The maps package was introduced in Go 1.21. Please ensure that the project's minimum Go version is at least 1.21 or update it accordingly to avoid build issues.

client/response.go (2)

59-80: Ensure safe usage of utils.UnsafeString in Headers method

The Headers method uses utils.UnsafeString to convert byte slices to strings. While this is efficient, ensure that the byte slices are not modified elsewhere to prevent unexpected behavior due to string aliasing.


83-85: Documentation for Cookies method is clear and informative

The updated comments provide essential information about the validity and usage of the returned cookies, promoting correct usage.

Comment on lines +463 to +465
for i := 0; i < b.N; i++ {
for range req.Cookies() {
}
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

Empty loop in Benchmark_Request_Cookies may lead to misleading results

The inner loop in the Benchmark_Request_Cookies function is empty. This may cause inaccurate benchmarking due to compiler optimizations. Add operations inside the loop to measure cookie iteration performance.

Apply this diff:

 for i := 0; i < b.N; i++ {
-    for range req.Cookies() {
-    }
+    for key, value := range req.Cookies() {
+        _ = key
+        _ = value
+    }
 }
📝 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
for i := 0; i < b.N; i++ {
for range req.Cookies() {
}
for i := 0; i < b.N; i++ {
for key, value := range req.Cookies() {
_ = key
_ = value
}
🧰 Tools
🪛 golangci-lint (1.62.2)

[warning] 464-464: empty-block: this block is empty, you can remove it

(revive)

Comment on lines +574 to +575
for range req.PathParams() {
}
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

Empty loop in Benchmark_Request_PathParams may lead to misleading results

The inner loop in the Benchmark_Request_PathParams function is empty. This could lead to the compiler optimizing it away. Include meaningful operations to benchmark path parameter iteration effectively.

Apply this diff:

 for i := 0; i < b.N; i++ {
-    for range req.PathParams() {
-    }
+    for key, value := range req.PathParams() {
+        _ = key
+        _ = value
+    }
 }
📝 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
for range req.PathParams() {
}
for key, value := range req.PathParams() {
_ = key
_ = value
}
🧰 Tools
🪛 golangci-lint (1.62.2)

[warning] 574-574: empty-block: this block is empty, you can remove it

(revive)

Comment on lines +348 to +350
for i := 0; i < b.N; i++ {
for range req.Params() {
}
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

Empty loop in Benchmark_Request_Params may lead to misleading results

The inner loop in the Benchmark_Request_Params function is empty. This could result in the compiler optimizing out the loop. Include meaningful operations inside the loop to accurately benchmark parameter iteration.

Apply this diff:

 for i := 0; i < b.N; i++ {
-    for range req.Params() {
-    }
+    for key, values := range req.Params() {
+        _ = key
+        _ = values
+    }
 }
📝 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
for i := 0; i < b.N; i++ {
for range req.Params() {
}
for i := 0; i < b.N; i++ {
for key, values := range req.Params() {
_ = key
_ = values
}
🧰 Tools
🪛 golangci-lint (1.62.2)

[warning] 349-349: empty-block: this block is empty, you can remove it

(revive)

Comment on lines +190 to +192
for range req.Headers() {
}
}
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

Empty loop in Benchmark_Request_Headers may lead to misleading results

The inner loop in the Benchmark_Request_Headers function is empty. This might cause the compiler to optimize away the loop, leading to inaccurate benchmarking. Consider performing an operation inside the loop to measure the performance effectively.

Apply this diff to include an operation inside the loop:

 for i := 0; i < b.N; i++ {
-    for range req.Headers() {
-    }
+    for key, values := range req.Headers() {
+        _ = key
+        _ = values
+    }
 }
📝 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
for range req.Headers() {
}
}
for key, values := range req.Headers() {
_ = key
_ = values
}
}
🧰 Tools
🪛 golangci-lint (1.62.2)

[warning] 190-190: empty-block: this block is empty, you can remove it

(revive)

Comment on lines +1382 to +1383
for range req.FormDatas() {
}
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

Empty loop in Benchmark_Request_FormDatas may lead to misleading results

The inner loop in the Benchmark_Request_FormDatas function is empty. This may result in the compiler optimizing away the loop, leading to inaccurate benchmarks. Add operations inside the loop to measure form data iteration performance.

Apply this diff:

 for i := 0; i < b.N; i++ {
-    for range req.FormDatas() {
-    }
+    for key, values := range req.FormDatas() {
+        _ = key
+        _ = values
+    }
 }

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

client/hooks.go Outdated Show resolved Hide resolved
Comment on lines +273 to +274
for range resp.Headers() {
}
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

Empty loop in Benchmark_Headers may lead to misleading results

The inner loop in the Benchmark_Headers function is empty. This can cause the compiler to optimize it away, making the benchmark ineffective. Include operations inside the loop to measure header iteration performance accurately.

Apply this diff:

 for i := 0; i < b.N; i++ {
-    for range resp.Headers() {
-    }
+    for key, values := range resp.Headers() {
+        _ = key
+        _ = values
+    }
 }

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

🧰 Tools
🪛 golangci-lint (1.62.2)

[warning] 273-273: empty-block: this block is empty, you can remove it

(revive)

for k, v := range resp.Headers() {
headers[k] = make([]string, 0)
for _, value := range v {
fmt.Print(string(value))
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 fmt.Print statement from test to avoid cluttering output

Using fmt.Print in tests can clutter the test output and is generally discouraged. Instead, use assertions to validate the values.

Apply this diff to remove the print statement:

 for _, value := range v {
-    fmt.Print(string(value))
     headers[k] = append(headers[k], string(value))
 }

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

🧰 Tools
🪛 golangci-lint (1.62.2)

[warning] 229-229: unhandled-error: Unhandled error in call to function fmt.Print

(revive)


229-229: use of fmt.Print forbidden by pattern ^fmt\.Print(f|ln)?$

(forbidigo)


229-229: Error return value of fmt.Print is not checked

(errcheck)


229-229: unnecessary conversion

(unconvert)

Comment on lines +873 to +879
keys := make([]string, f.Len())
f.VisitAll(func(key, value []byte) {
keys = append(keys, utils.UnsafeString(key))
})

return slices.Compact(keys)
}
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

Optimize slice initialization and address unused parameter in FormData.Keys

Similar to the QueryParam.Keys method, initialize the keys slice with zero length and capacity of f.Len(). Also, rename the unused value parameter to _.

Apply this diff:

 func (f *FormData) Keys() []string {
-    keys := make([]string, f.Len())
+    keys := make([]string, 0, f.Len())
-    f.VisitAll(func(key, value []byte) {
+    f.VisitAll(func(key, _ []byte) {
         keys = append(keys, utils.UnsafeString(key))
     })
     return slices.Compact(keys)
 }
📝 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
keys := make([]string, f.Len())
f.VisitAll(func(key, value []byte) {
keys = append(keys, utils.UnsafeString(key))
})
return slices.Compact(keys)
}
keys := make([]string, 0, f.Len())
f.VisitAll(func(key, _ []byte) {
keys = append(keys, utils.UnsafeString(key))
})
return slices.Compact(keys)
}
🧰 Tools
🪛 golangci-lint (1.62.2)

875-875: append to slice keys with non-zero initialized length

(makezero)

🪛 GitHub Check: lint

[failure] 874-874:
unused-parameter: parameter 'value' seems to be unused, consider removing or renaming it as _ (revive)


[failure] 875-875:
append to slice keys with non-zero initialized length (makezero)

Comment on lines +731 to +739
// Keys method returns all keys in the query params.
func (f *QueryParam) Keys() []string {
keys := make([]string, f.Len())
f.VisitAll(func(key, value []byte) {
keys = append(keys, utils.UnsafeString(key))
})

return slices.Compact(keys)
}
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

Optimize slice initialization and address unused parameter in QueryParam.Keys

In the Keys method, the slice keys is initialized with a non-zero length and then appended to, leading to unintended zero values at the beginning. Additionally, the value parameter in VisitAll is unused.

Apply this diff:

 func (f *QueryParam) Keys() []string {
-    keys := make([]string, f.Len())
+    keys := make([]string, 0, f.Len())
-    f.VisitAll(func(key, value []byte) {
+    f.VisitAll(func(key, _ []byte) {
         keys = append(keys, utils.UnsafeString(key))
     })
     return slices.Compact(keys)
 }
📝 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
// Keys method returns all keys in the query params.
func (f *QueryParam) Keys() []string {
keys := make([]string, f.Len())
f.VisitAll(func(key, value []byte) {
keys = append(keys, utils.UnsafeString(key))
})
return slices.Compact(keys)
}
// Keys method returns all keys in the query params.
func (f *QueryParam) Keys() []string {
keys := make([]string, 0, f.Len())
f.VisitAll(func(key, _ []byte) {
keys = append(keys, utils.UnsafeString(key))
})
return slices.Compact(keys)
}
🧰 Tools
🪛 golangci-lint (1.62.2)

735-735: append to slice keys with non-zero initialized length

(makezero)

🪛 GitHub Check: lint

[failure] 734-734:
unused-parameter: parameter 'value' seems to be unused, consider removing or renaming it as _ (revive)


[failure] 735-735:
append to slice keys with non-zero initialized length (makezero)

Copy link
Contributor

@github-actions github-actions bot left a comment

Choose a reason for hiding this comment

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

⚠️ Performance Alert ⚠️

Possible performance regression was detected for benchmark.
Benchmark result of this commit is worse than the previous benchmark result exceeding threshold 1.50.

Benchmark suite Current: 26a3439 Previous: 9a2ceb7 Ratio
BenchmarkDecoderedirectionMsgs 13.81 ns/op 72.44 MB/s 0 B/op 0 allocs/op 8.381 ns/op 119.32 MB/s 0 B/op 0 allocs/op 1.65
BenchmarkDecoderedirectionMsgs - ns/op 13.81 ns/op 8.381 ns/op 1.65

This comment was automatically generated by workflow using github-action-benchmark.

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
@gaby gaby added the v3 label Dec 2, 2024
@gaby gaby added this to the v3 milestone Dec 2, 2024
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.

🧹 [Maintenance]: Add a straightforward approach for accessing response headers in *fiber.Agent
2 participants