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

🔥 feat: Add support for iterator methods to Fiber client #3228

Merged
merged 15 commits into from
Dec 10, 2024

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, AllFormData; 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.
Makefile Updated comment for markdown target to reflect change in required tool from markdownlint-cli to markdownlint-cli2.
docs/client/request.md Enhanced documentation for Request struct with new methods for headers, parameters, cookies, and form data.
docs/client/response.md Updated documentation for Response struct to include new Headers method and clarify Cookies method.

Assessment against linked issues

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

Possibly related PRs

Suggested reviewers

  • sixcolors
  • gaby
  • efectn

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! 🐇✨


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 generate docstrings to generate docstrings for this PR. (Experiment)
  • @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.

@efectn efectn force-pushed the client-iterators-2 branch from fe2a14f to 7578ae3 Compare December 2, 2024 09:09
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.

client/request_test.go Outdated Show resolved Hide resolved
client/request_test.go Outdated Show resolved Hide resolved
client/request_test.go Outdated Show resolved Hide resolved
client/request_test.go Outdated Show resolved Hide resolved
client/request_test.go Outdated Show resolved Hide resolved
client/hooks.go Outdated Show resolved Hide resolved
client/response_test.go Outdated Show resolved Hide resolved
client/response_test.go Outdated Show resolved Hide resolved
client/request.go Outdated Show resolved Hide resolved
client/request.go Outdated Show resolved Hide resolved
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: 65c0448 Previous: 70a06c5 Ratio
Benchmark_Compress_Levels/Brotli_LevelBestCompression - B/op 5 B/op 0 B/op +∞

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

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

165-168: Use consistent casing for keys in test data

In the test setups, keys are sometimes mixed case (e.g., "foo", "bar"). Consider using consistent casing for keys to enhance readability and avoid confusion, even though map keys are case-sensitive.

Example adjustment:

-req.AddHeaders(map[string][]string{
-    "foo": {"bar", "fiber"},
-    "bar": {"foo"},
+req.AddHeaders(map[string][]string{
+    "Foo": {"bar", "fiber"},
+    "Bar": {"foo"},
 })

Also applies to: 326-329, 444-447, 556-559, 1365-1368


766-770: Check file readers in Test_Request_Files for completeness

In the Test_Request_Files function, the reader fields of the files are nil. If the intention is to test file readers, consider adding files with non-nil readers and include assertions to verify their contents.


331-338: Ensure accurate variable naming for clarity in tests

Variables like pathParams are used in contexts where they represent different data types (e.g., query params, cookies). Consider renaming these variables to reflect their actual content for better readability.

Example adjustment:

-pathParams := maps.Collect(req.Params())
+params := maps.Collect(req.Params())

-require.Contains(t, pathParams["foo"], "bar")
-require.Contains(t, pathParams["foo"], "fiber")
-require.Contains(t, pathParams["bar"], "foo")
+require.Contains(t, params["foo"], "bar")
+require.Contains(t, params["foo"], "fiber")
+require.Contains(t, params["bar"], "foo")

-require.Len(t, pathParams, 2)
+require.Len(t, params, 2)

Also applies to: 449-455, 563-567, 1372-1377


Line range hint 218-221: Defer response closure to prevent resource leaks in tests

After obtaining the response, it's good practice to defer the closure immediately to ensure resources are released properly, especially if the test could fail before the explicit resp.Close() call.

Apply this diff:

 resp, err := AcquireRequest().
     SetClient(client).
     Get("http://example.com")

+defer resp.Close()

 require.NoError(t, err)
-// ...
-resp.Close()

Also applies to: 443-448, 760-762

client/response_test.go (2)

203-234: Defer response closure to ensure resources are released

In Test_Response_Headers, defer the resp.Close() immediately after the response is acquired to guarantee that resources are properly released, even if an assertion fails.

Apply this diff:

 resp, err := AcquireRequest().
     SetClient(client).
     Get("http://example.com")
+defer resp.Close()

 require.NoError(t, err)
 // ...
-resp.Close()

229-231: Remove unnecessary blank lines to improve readability

In Test_Response_Headers, there are extra blank lines before and after the assertions. Removing these can make the test code more concise and readable.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

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

📒 Files selected for processing (3)
  • client/request.go (9 hunks)
  • client/request_test.go (7 hunks)
  • client/response_test.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • client/request.go
🔇 Additional comments (2)
client/request_test.go (2)

179-195: Benchmark loops are correctly preventing compiler optimizations

The inner loops in the benchmark functions appropriately assign variables to _, ensuring that the compiler does not optimize away the loop body. This allows for accurate benchmarking of the iteration methods.

Also applies to: 340-356, 457-473, 569-585, 1379-1395


8-8: ⚠️ Potential issue

Verify Go version compatibility due to usage of maps package

The maps package was introduced in Go 1.19. Ensure that the project's minimum Go version is set to 1.19 or higher in go.mod to avoid build issues on older Go versions.

Run the following script to check the Go version specified in go.mod:

✅ Verification successful

Go version compatibility verified for maps package usage

The project's go.mod specifies Go 1.23, which is well above the minimum required version (1.19) for using the maps package. No compatibility issues.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check the minimum required Go version in go.mod
grep '^go ' go.mod

Length of output: 28

client/response_test.go Outdated Show resolved Hide resolved
Copy link

codecov bot commented Dec 4, 2024

Codecov Report

Attention: Patch coverage is 71.59091% with 25 lines in your changes missing coverage. Please review.

Project coverage is 82.69%. Comparing base (27cfd3c) to head (40361f9).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
client/request.go 73.23% 12 Missing and 7 partials ⚠️
client/hooks.go 25.00% 1 Missing and 2 partials ⚠️
client/response.go 76.92% 2 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #3228      +/-   ##
==========================================
- Coverage   82.81%   82.69%   -0.13%     
==========================================
  Files         115      115              
  Lines       11302    11377      +75     
==========================================
+ Hits         9360     9408      +48     
- Misses       1543     1561      +18     
- Partials      399      408       +9     
Flag Coverage Δ
unittests 82.69% <71.59%> (-0.13%) ⬇️

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.

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 (5)
docs/client/response.md (2)

97-129: Documentation for Headers() method is well structured but needs minor grammar fixes.

The documentation is clear and includes all necessary components (signature, description, example). However, there are a few grammatical improvements needed:

Apply these changes to improve readability:

-Headers returns all headers in the response using an iterator. You can use `maps.Collect()` to collect all headers into a map.
+Headers returns all headers in the response using an iterator. You can use `maps.Collect()` to collect all headers into a map.
-The returned value is valid until the response object is released. Any future calls to Headers method will return the modified value.
+The returned value is valid until the response object is released. Any future calls to the Headers method will return the modified value.
🧰 Tools
🪛 LanguageTool

[uncategorized] ~100-~100: Possible missing article found.
Context: ...object is released. Any future calls to Headers method will return the modified value. ...

(AI_HYDRA_LEO_MISSING_THE)


[uncategorized] ~100-~100: Possible missing article found.
Context: ...ified value. Do not store references to returned value. Make copies instead. ```go titl...

(AI_HYDRA_LEO_MISSING_THE)


133-133: Fix grammar in Cookies() method documentation.

Apply this change:

-The returned value is valid until the response object is released. Any future calls to Cookies method will return the modified value.
+The returned value is valid until the response object is released. Any future calls to the Cookies method will return the modified value.
🧰 Tools
🪛 LanguageTool

[uncategorized] ~133-~133: It seems likely that a singular genitive (’s) apostrophe is missing.
Context: ...object is released. Any future calls to Cookies method will return the modified value. ...

(AI_HYDRA_LEO_APOSTROPHE_S_XS)


[uncategorized] ~133-~133: Possible missing article found.
Context: ...ified value. Do not store references to returned value. Make copies instead. ```go titl...

(AI_HYDRA_LEO_MISSING_THE)

docs/client/request.md (3)

214-245: Headers documentation is well structured but could benefit from more examples.

The documentation clearly explains the method's purpose and behavior. Consider adding examples that demonstrate:

  • Handling multiple header values
  • Case-insensitive header matching
  • Common use cases with maps.Collect()

885-893: Files method documentation needs more details.

The current documentation is minimal. Consider adding:

  • Example usage
  • Common file handling patterns
  • Best practices for memory management

1140-1147: Keys method documentation is consistent across QueryParam and FormData.

The documentation for Keys() method is clear and consistent between both types. However, consider adding examples to demonstrate practical usage.

Also applies to: 1327-1334

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between b4c7c54 and 0343f06.

📒 Files selected for processing (4)
  • Makefile (1 hunks)
  • client/response_test.go (1 hunks)
  • docs/client/request.md (8 hunks)
  • docs/client/response.md (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • Makefile
🧰 Additional context used
🪛 LanguageTool
docs/client/response.md

[uncategorized] ~100-~100: Possible missing article found.
Context: ...object is released. Any future calls to Headers method will return the modified value. ...

(AI_HYDRA_LEO_MISSING_THE)


[uncategorized] ~100-~100: Possible missing article found.
Context: ...ified value. Do not store references to returned value. Make copies instead. ```go titl...

(AI_HYDRA_LEO_MISSING_THE)


[uncategorized] ~133-~133: It seems likely that a singular genitive (’s) apostrophe is missing.
Context: ...object is released. Any future calls to Cookies method will return the modified value. ...

(AI_HYDRA_LEO_APOSTROPHE_S_XS)


[uncategorized] ~133-~133: Possible missing article found.
Context: ...ified value. Do not store references to returned value. Make copies instead. ```go titl...

(AI_HYDRA_LEO_MISSING_THE)

🔇 Additional comments (2)
client/response_test.go (2)

202-238: Test coverage for Headers() method is comprehensive.

The test effectively verifies:

  • Multiple values for the same header
  • Case-insensitive header keys
  • Proper header collection into a map

240-279: 🛠️ Refactor suggestion

Benchmark can be optimized to focus on header iteration.

The benchmark includes HTTP request overhead in each iteration. For more accurate header iteration performance measurement:

Apply this change:

 client := New().SetDial(server.dial())
 
-var err error
-var resp *Response
+resp, err := AcquireRequest().
+    SetClient(client).
+    Get("http://example.com")
+require.NoError(b, err)
+defer resp.Close()
+
+b.ResetTimer()
+b.ReportAllocs()
 
 for i := 0; i < b.N; i++ {
-    resp, err = AcquireRequest().
-        SetClient(client).
-        Get("http://example.com")
     for k, v := range resp.Headers() {
         _ = k
         _ = v
     }
-    resp.Close()
 }

Likely invalid or redundant comment.

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 (3)
docs/client/request.md (3)

356-357: Add "the" before "Params method"

For better readability and grammatical correctness, add the article "the" before "Params method".

-Any future calls to Params method will return the modified value.
+Any future calls to the Params method will return the modified value.
🧰 Tools
🪛 LanguageTool

[uncategorized] ~357-~357: Possible missing article found.
Context: ...object is released. Any future calls to Params method will return the modified value. ...

(AI_HYDRA_LEO_MISSING_THE)


547-551: Add usage examples for iterator methods

The Headers() method includes a complete example with output, but similar examples are missing for other iterator methods (Params, Cookies, PathParams, FormDatas, Files). Consider adding examples to demonstrate their usage with maps.Collect() for consistency.

Here's a template for the missing examples:

req := client.AcquireRequest()
defer client.ReleaseRequest(req)

// Add some test data
req.AddParam("page", "1")
req.AddParam("limit", "10")

// Use the iterator
for k, v := range req.Params() {
    fmt.Printf("Param Key: %s, Value: %v\n", k, v)
}

Also applies to: 628-632, 743-747, 886-891


216-217: Enhance clarity of iterator method warnings

The warning about value validity could be clearer and more actionable. Consider updating the warning message across all iterator methods to be more explicit about:

  1. Why storing references is dangerous
  2. How to properly handle the values

Example improved warning:

-The returned value is valid until the request object is released. Any future calls to the Headers method will return the modified value. Do not store references to returned value. Make copies instead.
+The returned iterator is only valid until the request object is released back to the pool. Storing references to the returned values may lead to data races or use-after-free issues. If you need to preserve the values, create a copy using maps.Collect() or similar methods immediately after iteration.

Also applies to: 356-357, 547-548, 628-629, 743-744, 886-887

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 0343f06 and bb43f28.

📒 Files selected for processing (1)
  • docs/client/request.md (8 hunks)
🧰 Additional context used
🪛 LanguageTool
docs/client/request.md

[uncategorized] ~357-~357: Possible missing article found.
Context: ...object is released. Any future calls to Params method will return the modified value. ...

(AI_HYDRA_LEO_MISSING_THE)

🔇 Additional comments (1)
docs/client/request.md (1)

Line range hint 214-1333: Documentation structure and content look good!

The documentation is well-structured and consistent across all methods. The new iterator methods and Keys() methods are properly documented with clear signatures and descriptions.

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.

Code looks good, just a rename and some docs comments.

docs/client/response.md Outdated Show resolved Hide resolved
docs/client/request.md Outdated Show resolved Hide resolved
docs/client/request.md Outdated Show resolved Hide resolved
docs/client/request.md Show resolved Hide resolved
docs/client/request.md Show resolved Hide resolved
client/request.go Outdated Show resolved Hide resolved
@gaby gaby changed the title client: add support for iterator methods 🔥 feat: Add support for iterator methods to Fiber client Dec 9, 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: 0

🧹 Outside diff range and nitpick comments (12)
client/request.go (4)

153-156: Improve performance by avoiding unnecessary slice copying in Headers

In the Headers method, copying the peekKeys slice into keys using copy is unnecessary and can be avoided. Since peekKeys is not modified within the method, you can iterate over it directly, which improves performance.

Apply this diff:

 func (r *Request) Headers() iter.Seq2[string, []string] {
     return func(yield func(string, []string) bool) {
-        peekKeys := r.header.PeekKeys()
-        keys := make([][]byte, len(peekKeys))
-        copy(keys, peekKeys) // It is necessary to have immutable byte slice.
+        keys := r.header.PeekKeys()

         for _, key := range keys {
🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 153-154: client/request.go#L153-L154
Added lines #L153 - L154 were not covered by tests


209-211: Simplify condition in Params to improve readability

The check if key == "" is unnecessary if empty keys are not expected. If empty keys are possible but should be skipped, consider documenting this behavior.

Apply this diff:

         for _, key := range keys {
-            if key == "" {
-                continue
-            }
🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 209-209: client/request.go#L209
Added line #L209 was not covered by tests


464-465: Avoid unnecessary function call in AllFormData

In the AllFormData method, calling Keys() creates an additional slice. You can optimize this by using VisitAll directly to iterate over the form data.

Apply this diff:

 func (r *Request) AllFormData() iter.Seq2[string, []string] {
     return func(yield func(string, []string) bool) {
-        keys := r.formData.Keys()

-        for _, key := range keys {
+        r.formData.VisitAll(func(keyBytes, _ []byte) {
+            key := utils.UnsafeString(keyBytes)

468-469: Simplify condition in AllFormData to improve readability

The check if key == "" may be unnecessary unless empty keys are expected. If they are not allowed, consider removing the check or adding validation when data is added.

Apply this diff:

             key := utils.UnsafeString(keyBytes)
-            if key == "" {
-                continue
-            }
🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 468-468: client/request.go#L468
Added line #L468 was not covered by tests

docs/client/request.md (8)

216-244: Provide an example of using maps.Collect() with Headers

The documentation mentions using maps.Collect() to collect all headers into a map but does not provide an example. Adding an example would help users understand how to utilize this function effectively.

Consider adding an example like:

headersMap := maps.Collect(req.Headers())

215-215: Clarify how to copy values from iter.Seq2

It's not clear how users should make copies of the returned values from the iterator to avoid storing references. Providing guidance or examples on copying data would improve the documentation.

You might explain that using maps.Collect() creates a copy of the data, thus avoiding the issue with storing references.


236-243: Remove unnecessary <details> tags in the example result

The usage of <details> tags around the example result adds unnecessary complexity to the documentation. Removing them will make the results immediately visible to the reader.

Apply this change:

  • Remove <details> and <summary> tags surrounding the result.

354-362: Provide an example of using maps.Collect() with Params

Similar to the Headers section, include an example demonstrating how to collect all parameters into a map using maps.Collect().

Add an example like:

paramsMap := maps.Collect(req.Params())

545-552: Include an example of collecting all cookies using maps.Collect()

To help users understand how to collect cookies into a map, provide an example in the Cookies section.

Example:

cookiesMap := maps.Collect(req.Cookies())

626-633: Add an example for collecting PathParams using maps.Collect()

Including an example will clarify how to use the iterator to collect path parameters into a map.

Example:

pathParamsMap := maps.Collect(req.PathParams())

741-748: Provide an example for AllFormData using maps.Collect()

An example would help users understand how to collect all form data into a map using the iterator.

Example:

formDataMap := maps.Collect(req.AllFormData())

884-892: Clarify the use of Files method and provide an example

The Files method returns a slice of pointers to File. Including an example will help users understand how to work with the returned files.

Example:

files := req.Files()
for _, file := range files {
    fmt.Printf("File Name: %s, Field Name: %s, Path: %s\n", file.name, file.fieldName, file.path)
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between bb43f28 and cd9b6c9.

📒 Files selected for processing (3)
  • client/request.go (9 hunks)
  • client/request_test.go (7 hunks)
  • docs/client/request.md (8 hunks)
🧰 Additional context used
🪛 GitHub Check: codecov/patch
client/request.go

[warning] 153-154: client/request.go#L153-L154
Added lines #L153 - L154 were not covered by tests


[warning] 209-209: client/request.go#L209
Added line #L209 was not covered by tests


[warning] 219-220: client/request.go#L219-L220
Added lines #L219 - L220 were not covered by tests


[warning] 317-318: client/request.go#L317-L318
Added lines #L317 - L318 were not covered by tests


[warning] 366-367: client/request.go#L366-L367
Added lines #L366 - L367 were not covered by tests


[warning] 468-468: client/request.go#L468
Added line #L468 was not covered by tests


[warning] 478-479: client/request.go#L478-L479
Added lines #L478 - L479 were not covered by tests

🔇 Additional comments (9)
client/request_test.go (6)

190-194: 🛠️ Refactor suggestion

Prevent compiler optimization in Benchmark_Request_Headers

The inner loop in Benchmark_Request_Headers assigns k and v but does not use them meaningfully, which may allow the compiler to optimize away the loop, resulting in inaccurate benchmark results.

Apply this diff to ensure the loop is not optimized out:

 for i := 0; i < b.N; i++ {
-    for k, v := range req.Headers() {
-        _ = k
-        _ = v
-    }
+    sum := 0
+    for k, v := range req.Headers() {
+        sum += len(k) + len(strings.Join(v, ""))
+    }
+    if sum == 0 {
+        b.Fail()
+    }
 }

350-355: 🛠️ Refactor suggestion

Prevent compiler optimization in Benchmark_Request_Params

The inner loop in Benchmark_Request_Params may be optimized away because k and v are assigned but not used in a meaningful way, potentially leading to misleading benchmark results.

Apply this diff:

 for i := 0; i < b.N; i++ {
-    for k, v := range req.Params() {
-        _ = k
-        _ = v
-    }
+    sum := 0
+    for k, v := range req.Params() {
+        sum += len(k)
+        for _, val := range v {
+            sum += len(val)
+        }
+    }
+    if sum == 0 {
+        b.Fail()
+    }
 }

467-472: 🛠️ Refactor suggestion

Prevent compiler optimization in Benchmark_Request_Cookies

The inner loop in Benchmark_Request_Cookies assigns k and v but does not use them meaningfully. This may cause the compiler to optimize away the loop, affecting the accuracy of your benchmark.

Apply this diff:

 for i := 0; i < b.N; i++ {
-    for k, v := range req.Cookies() {
-        _ = k
-        _ = v
-    }
+    sum := 0
+    for k, v := range req.Cookies() {
+        sum += len(k) + len(v)
+    }
+    if sum == 0 {
+        b.Fail()
+    }
 }

579-584: 🛠️ Refactor suggestion

Prevent compiler optimization in Benchmark_Request_PathParams

The inner loop in Benchmark_Request_PathParams may be optimized away since k and v are not used meaningfully, which can lead to inaccurate benchmarking results.

Apply this diff:

 for i := 0; i < b.N; i++ {
-    for k, v := range req.PathParams() {
-        _ = k
-        _ = v
-    }
+    sum := 0
+    for k, v := range req.PathParams() {
+        sum += len(k) + len(v)
+    }
+    if sum == 0 {
+        b.Fail()
+    }
 }

782-787: 🛠️ Refactor suggestion

Prevent compiler optimization in Benchmark_Request_Files

The inner loop in Benchmark_Request_Files does not use the variables k and v in a way that prevents compiler optimization, which may lead to misleading benchmark results.

Apply this diff:

 for i := 0; i < b.N; i++ {
-    for k, v := range req.Files() {
-        _ = k
-        _ = v
-    }
+    sum := 0
+    for _, file := range req.Files() {
+        sum += len(file.name) + len(file.fieldName) + len(file.path)
+    }
+    if sum == 0 {
+        b.Fail()
+    }
 }

1389-1394: 🛠️ Refactor suggestion

Prevent compiler optimization in Benchmark_Request_AllFormData

The inner loop in Benchmark_Request_AllFormData may be optimized away because k and v are not used meaningfully, potentially affecting the benchmark accuracy.

Apply this diff:

 for i := 0; i < b.N; i++ {
-    for k, v := range req.AllFormData() {
-        _ = k
-        _ = v
-    }
+    sum := 0
+    for k, v := range req.AllFormData() {
+        sum += len(k)
+        for _, val := range v {
+            sum += len(val)
+        }
+    }
+    if sum == 0 {
+        b.Fail()
+    }
 }
client/request.go (2)

734-738: 🛠️ Refactor suggestion

Address unused parameter and slice initialization in QueryParam.Keys

The parameter _ []byte in VisitAll is unused. Rename it to _ to indicate that it's intentionally unused. Additionally, initialize the keys slice with zero length and capacity of p.Len() to avoid pre-populating it with empty strings.

Apply this diff:

 func (p *QueryParam) Keys() []string {
-    keys := make([]string, p.Len())
-    p.VisitAll(func(key, value []byte) {
+    keys := make([]string, 0, p.Len())
+    p.VisitAll(func(key, _ []byte) {
         keys = append(keys, utils.UnsafeString(key))
     })
     return slices.Compact(keys)

874-878: 🛠️ Refactor suggestion

Address unused parameter and slice initialization in FormData.Keys

The parameter _ []byte in VisitAll is unused. Rename it to _ to indicate that it's intentionally unused. Also, initialize the keys slice with zero length and capacity of f.Len() to prevent pre-filling it with default zero values.

Apply this diff:

 func (f *FormData) Keys() []string {
-    keys := make([]string, f.Len())
-    f.VisitAll(func(key, value []byte) {
+    keys := make([]string, 0, f.Len())
+    f.VisitAll(func(key, _ []byte) {
         keys = append(keys, utils.UnsafeString(key))
     })
     return slices.Compact(keys)
docs/client/request.md (1)

216-244: 🛠️ Refactor suggestion

Correct the pluralization of FormDatas to FormData

The term FormDatas is not standard English. It should be FormData, even when referring to multiple entries.

Apply this change throughout the documentation:

  • Replace FormDatas with AllFormData or FormData as appropriate.

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 (3)
docs/client/request.md (3)

214-267: Enhance iterator methods documentation with more detailed examples

The documentation for the new iterator methods (Headers, Params, Cookies, PathParams, AllFormData, Files) could be improved in several areas:

  1. Add examples showing how to safely copy values when needed
  2. Explain the relationship between maps.Collect() and the iterator interface
  3. Include examples demonstrating iteration with both range-based loops and maps.Collect()

Consider adding a common section explaining the iterator pattern and value copying, then reference it from each method's documentation. For example:

### Working with Iterators

Fiber's iterator methods return a `iter.Seq2` interface that allows efficient iteration over key-value pairs. There are two ways to work with iterators:

1. Using range-based loops (memory efficient):
```go
for k, v := range req.Headers() {
    // Process key-value pairs
}
  1. Collecting all values into a map (creates a copy):
headers := maps.Collect(req.Headers())

Note: Always use maps.Collect() when you need to store the values for later use, as the iterator's values are only valid until the request is released.



Also applies to: 377-384, 568-574, 649-655, 764-770, 907-914

<details>
<summary>🧰 Tools</summary>

<details>
<summary>🪛 LanguageTool</summary>

[uncategorized] ~217-~217: Possible missing article found.
Context: ...object is released. Any future calls to Headers method will return the modified value. ...

(AI_HYDRA_LEO_MISSING_THE)

---

[uncategorized] ~217-~217: Possible missing article found.
Context: ...ified value. Do not store references to returned value. Make copies instead.  ```go titl...

(AI_HYDRA_LEO_MISSING_THE)

</details>

</details>

---

`217-217`: **Improve grammar with proper article usage**

Add "the" in the following sentences for better readability:

```diff
-Any future calls to Headers method will return the modified value.
+Any future calls to the Headers method will return the modified value.

-Any future calls to Params method will return the modified value.
+Any future calls to the Params method will return the modified value.

-Do not store references to returned value.
+Do not store references to the returned value.

Also applies to: 380-380, 910-910

🧰 Tools
🪛 LanguageTool

[uncategorized] ~217-~217: Possible missing article found.
Context: ...object is released. Any future calls to Headers method will return the modified value. ...

(AI_HYDRA_LEO_MISSING_THE)


[uncategorized] ~217-~217: Possible missing article found.
Context: ...ified value. Do not store references to returned value. Make copies instead. ```go titl...

(AI_HYDRA_LEO_MISSING_THE)


235-243: Consider standardizing the details/summary sections

While the details/summary sections help manage documentation length, they should follow a consistent pattern. Consider:

  1. Using a more descriptive summary text (e.g., "Example Output" instead of "Click here to see the result")
  2. Adding syntax highlighting hints to all code blocks within details sections

Example improvement:

-<summary>Click here to see the result</summary>
+<summary>Example Output</summary>

 ```sh

Also applies to: 258-266

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between cd9b6c9 and 0b71163.

📒 Files selected for processing (2)
  • docs/client/request.md (8 hunks)
  • docs/client/response.md (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • docs/client/response.md
🧰 Additional context used
🪛 LanguageTool
docs/client/request.md

[uncategorized] ~217-~217: Possible missing article found.
Context: ...object is released. Any future calls to Headers method will return the modified value. ...

(AI_HYDRA_LEO_MISSING_THE)


[uncategorized] ~217-~217: Possible missing article found.
Context: ...ified value. Do not store references to returned value. Make copies instead. ```go titl...

(AI_HYDRA_LEO_MISSING_THE)


[uncategorized] ~380-~380: Possible missing article found.
Context: ...object is released. Any future calls to Params method will return the modified value. ...

(AI_HYDRA_LEO_MISSING_THE)


[uncategorized] ~380-~380: Possible missing article found.
Context: ...ified value. Do not store references to returned value. Make copies instead. ```go titl...

(AI_HYDRA_LEO_MISSING_THE)


[uncategorized] ~910-~910: Possible missing article found.
Context: ...ified value. Do not store references to returned value. Make copies instead. ```go titl...

(AI_HYDRA_LEO_MISSING_THE)

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

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 (4)
docs/client/request.md (4)

214-267: Ensure consistent documentation across iterator methods

While the Headers() method has comprehensive examples including maps.Collect() usage, other iterator methods (Params, Cookies, PathParams, AllFormData, Files) lack similar detailed examples. Consider adding consistent examples for all iterator methods to maintain documentation parity.

Also applies to: 377-384, 568-574, 649-655, 764-770, 907-914

🧰 Tools
🪛 LanguageTool

[uncategorized] ~217-~217: Possible missing article found.
Context: ...object is released. Any future calls to Headers method will return the modified value. ...

(AI_HYDRA_LEO_MISSING_THE)


[uncategorized] ~217-~217: Possible missing article found.
Context: ...ified value. Do not store references to returned value. Make copies instead. ```go titl...

(AI_HYDRA_LEO_MISSING_THE)


Line range hint 594-622: Fix inconsistent example response

The example response doesn't match the example code. The code sets cookies "cookie1" and "cookie2", but the response shows a different cookie "test".

Update the example response to match the code:

 {
   "cookies": {
-    "test": "123"
+    "cookie1": "value1",
+    "cookie2": "value2"
   }
 }

216-217: Fix grammar in documentation

Add missing articles in the following sentences:

  • "Any future calls to the Headers method..."
  • "Any future calls to the Params method..."
  • "Do not store references to the returned value..."

Also applies to: 379-380, 909-910

🧰 Tools
🪛 LanguageTool

[uncategorized] ~217-~217: Possible missing article found.
Context: ...object is released. Any future calls to Headers method will return the modified value. ...

(AI_HYDRA_LEO_MISSING_THE)


[uncategorized] ~217-~217: Possible missing article found.
Context: ...ified value. Do not store references to returned value. Make copies instead. ```go titl...

(AI_HYDRA_LEO_MISSING_THE)


Line range hint 276-313: Add error handling examples

The examples demonstrate successful cases but don't show how to handle common errors. Consider adding error handling examples for scenarios like:

  • Network timeouts
  • Invalid file paths
  • Malformed data

Example structure:

req := client.AcquireRequest()
defer client.ReleaseRequest(req)

resp, err := req.Post("https://httpbin.org/post")
if err != nil {
    switch {
    case errors.Is(err, ErrTimeout):
        // Handle timeout
    case errors.Is(err, ErrInvalidPath):
        // Handle invalid path
    default:
        // Handle other errors
    }
    return
}

Also applies to: 780-824, 932-969, 971-1014

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 0b71163 and fa4c54a.

📒 Files selected for processing (2)
  • docs/client/request.md (20 hunks)
  • docs/client/response.md (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • docs/client/response.md
🧰 Additional context used
🪛 LanguageTool
docs/client/request.md

[uncategorized] ~217-~217: Possible missing article found.
Context: ...object is released. Any future calls to Headers method will return the modified value. ...

(AI_HYDRA_LEO_MISSING_THE)


[uncategorized] ~217-~217: Possible missing article found.
Context: ...ified value. Do not store references to returned value. Make copies instead. ```go titl...

(AI_HYDRA_LEO_MISSING_THE)


[uncategorized] ~380-~380: Possible missing article found.
Context: ...object is released. Any future calls to Params method will return the modified value. ...

(AI_HYDRA_LEO_MISSING_THE)


[uncategorized] ~380-~380: Possible missing article found.
Context: ...ified value. Do not store references to returned value. Make copies instead. ```go titl...

(AI_HYDRA_LEO_MISSING_THE)


[uncategorized] ~910-~910: Possible missing article found.
Context: ...ified value. Do not store references to returned value. Make copies instead. ```go titl...

(AI_HYDRA_LEO_MISSING_THE)

// You can use maps.Collect() to collect all cookies into a map.
func (r *Request) Cookies() iter.Seq2[string, string] {
return func(yield func(string, string) bool) {
r.cookies.VisitAll(func(key, val string) {
Copy link
Contributor

Choose a reason for hiding this comment

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

VisitAll in its current form does not support early returns. If the caller of the iterator stops iterating early (e.g. by break in for range), yield would be called again after it returned false, and this causes a runtime panic.

Please update VisitAll to support early returns, and add a test to verify that stopping the iterator early works.

// You can use maps.Collect() to collect all cookies into a map.
func (r *Request) PathParams() iter.Seq2[string, string] {
return func(yield func(string, string) bool) {
r.path.VisitAll(func(key, val string) {
Copy link
Contributor

Choose a reason for hiding this comment

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

Same as the above.

Copy link
Member Author

Choose a reason for hiding this comment

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

Same as the above.

Thanks for the report. Will fix it

@coderabbitai coderabbitai bot mentioned this pull request Dec 20, 2024
30 tasks
@efectn efectn deleted the client-iterators-2 branch December 31, 2024 16:02
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]: Add a straightforward approach for accessing response headers in *fiber.Agent
4 participants