-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
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
Conversation
WalkthroughThe pull request introduces significant enhancements to the handling of HTTP requests and responses in the Changes
Assessment against linked issues
Possibly related PRs
Suggested reviewers
Poem
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? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
fe2a14f
to
7578ae3
Compare
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 10
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
⚠️ 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>
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
🧹 Outside diff range and nitpick comments (6)
client/request_test.go (4)
165-168
: Use consistent casing for keys in test dataIn 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 inTest_Request_Files
for completenessIn the
Test_Request_Files
function, thereader
fields of the files arenil
. 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 testsVariables 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 testsAfter 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 releasedIn
Test_Response_Headers
, defer theresp.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 readabilityIn
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
📒 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
:
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
Codecov ReportAttention: Patch coverage is
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
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Sentry. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
🧹 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
📒 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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
🧹 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 methodsThe 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 warningsThe warning about value validity could be clearer and more actionable. Consider updating the warning message across all iterator methods to be more explicit about:
- Why storing references is dangerous
- 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
📒 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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Code looks good, just a rename and some docs comments.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
🧹 Outside diff range and nitpick comments (12)
client/request.go (4)
153-156
: Improve performance by avoiding unnecessary slice copying inHeaders
In the
Headers
method, copying thepeekKeys
slice intokeys
usingcopy
is unnecessary and can be avoided. SincepeekKeys
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 inParams
to improve readabilityThe 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 inAllFormData
In the
AllFormData
method, callingKeys()
creates an additional slice. You can optimize this by usingVisitAll
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 inAllFormData
to improve readabilityThe 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 testsdocs/client/request.md (8)
216-244
: Provide an example of usingmaps.Collect()
withHeaders
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 fromiter.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 resultThe 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 usingmaps.Collect()
withParams
Similar to the
Headers
section, include an example demonstrating how to collect all parameters into a map usingmaps.Collect()
.Add an example like:
paramsMap := maps.Collect(req.Params())
545-552
: Include an example of collecting all cookies usingmaps.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 collectingPathParams
usingmaps.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 forAllFormData
usingmaps.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 ofFiles
method and provide an exampleThe
Files
method returns a slice of pointers toFile
. 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
📒 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
withAllFormData
orFormData
as appropriate.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
🧹 Outside diff range and nitpick comments (3)
docs/client/request.md (3)
214-267
: Enhance iterator methods documentation with more detailed examplesThe documentation for the new iterator methods (Headers, Params, Cookies, PathParams, AllFormData, Files) could be improved in several areas:
- Add examples showing how to safely copy values when needed
- Explain the relationship between
maps.Collect()
and the iterator interface- 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 }
- 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 sectionsWhile the details/summary sections help manage documentation length, they should follow a consistent pattern. Consider:
- Using a more descriptive summary text (e.g., "Example Output" instead of "Click here to see the result")
- 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> ```shAlso applies to: 258-266
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 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)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
👍 LGTM
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
🧹 Outside diff range and nitpick comments (4)
docs/client/request.md (4)
214-267
: Ensure consistent documentation across iterator methodsWhile 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 responseThe 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 documentationAdd 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 examplesThe 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
📒 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) { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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) { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Same as the above.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Same as the above.
Thanks for the report. Will fix it
Description
parserRequestFile
logic using io.CopyTodo:
Fixes #3184
Changes introduced
Type of change
Checklist
/docs/
directory for Fiber's documentation.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