🐛 fix: Enhance Body handling in setConfigToRequest for better type su…#3820
🐛 fix: Enhance Body handling in setConfigToRequest for better type su…#3820ReneWerner87 merged 4 commits intogofiber:mainfrom
Conversation
|
Thanks for opening this pull request! 🎉 Please check out our contributing guidelines. If you need help or want to chat with us, join us on Discord https://gofiber.io/discord |
|
Note Other AI code review bot(s) detectedCodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review. WalkthroughsetConfigToRequest now preserves multiple Body representations: Changes
Sequence Diagram(s)sequenceDiagram
participant Caller as Caller
participant Func as setConfigToRequest
participant Req as Request
Caller->>Func: call with cfg (cfg.Body may be nil or set)
Func->>Func: if cfg.Body != nil
alt Body is `[]byte`
Func->>Req: SetRawBody(cfg.Body)
Note right of Req #DFF2E1: raw bytes stored
else Body is `string`
Func->>Func: convert string -> []byte
Func->>Req: SetRawBody(bytes)
Note right of Req #DFF2E1: string converted to bytes
else Body is other type
Func->>Req: SetJSON(cfg.Body)
Note right of Req #FFF3D9: value stored for JSON
end
Func-->>Caller: return early (skip FormData/File handling)
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20–25 minutes
Suggested reviewers
Poem
Pre-merge checks and finishing touches❌ Failed checks (2 warnings)
✅ Passed checks (1 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
Summary of ChangesHello @K0ng2, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed! This pull request refines the Highlights
Using Gemini Code AssistThe full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips. Invoking Gemini You can request assistance from Gemini at any point by creating a comment using either
Customization To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a Limitations & Feedback Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here. You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension. Footnotes
|
There was a problem hiding this comment.
Code Review
This pull request enhances request body handling by allowing []byte and string types to be set as raw bodies, which is a great improvement for flexibility. However, the current implementation introduces a regression by removing a crucial return statement. This change breaks the documented priority where Body should take precedence over FormData and File, potentially causing the request body to be unintentionally overwritten. I've added a comment with a suggested fix to restore the correct behavior.
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (2)
client/client.go (2)
705-712: Add json.RawMessage fast‑pathjson.RawMessage (defined type over []byte) won’t match case []byte in a type switch, so it currently falls into SetJSON. If the intent is to allow raw JSON bytes too, add an explicit case.
switch v := cfg.Body.(type) { + case json.RawMessage: + req.SetRawBody(v) case []byte: req.SetRawBody(v) case string: req.SetRawBody([]byte(v)) default: req.SetJSON(cfg.Body) }
705-712: Content‑Type with raw bodiesWhen using []byte/string, Content‑Type is not auto‑set (unlike SetJSON). This may break callers who relied on implicit application/json for strings. Either:
- set a sensible default if header is absent (text/plain; charset=utf-8 for string, application/octet-stream for []byte), or
- clearly document that callers must set Content‑Type explicitly when passing raw bodies.
Add/adjust tests and release notes to reflect this change.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
client/client.go(1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.go
📄 CodeRabbit inference engine (AGENTS.md)
**/*.go: Apply formatting using gofumpt (Make target: format)
Optimize struct field alignment using betteralign (Make target: betteralign)
Modernize code using gopls modernize (Make target: modernize)
Files:
client/client.go
🔇 Additional comments (1)
client/client.go (1)
704-724: Breaking change verified: no problematic usages foundComprehensive repo scan completed:
- Found only 1 usage of string Body in config:
client/client_test.go:2095- That test already expects raw encoding (
"test"→"test", not JSON)- No tests or code found expecting JSON encoding of string Body
- No integration tests or examples that would break
- Code change at lines 704-724 correctly implements the raw body behavior
The breaking change is sound and the single affected usage is already properly tested for the new behavior.
There was a problem hiding this comment.
Pull Request Overview
This PR enhances the setConfigToRequest function to support multiple body types beyond JSON. Previously, all non-nil bodies were JSON-serialized. Now, []byte and string bodies are sent as raw data, while other types continue to use JSON encoding.
Key changes:
- Added type switch to differentiate between raw bytes, strings, and other body types
- Removed early return statement to allow proper flow through the configuration function
|
@codex Review this implementation:
|
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
…proved type handling
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (1)
client/client_test.go (1)
2091-2133: Consider adding edge case tests for body handling.The current tests provide solid coverage for the happy path scenarios (string, []byte, struct, map). However, consider adding tests for edge cases to ensure robust handling:
nilbody value- Empty string
""- Empty byte slice
[]byte("")or[]byte{}- Potentially other types that might be passed (e.g.,
io.Readerif supported)These edge cases could reveal boundary conditions in the implementation.
Would you like me to generate additional test cases for these edge cases?
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
client/client_test.go(1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.go
📄 CodeRabbit inference engine (AGENTS.md)
**/*.go: Apply formatting using gofumpt (Make target: format)
Optimize struct field alignment using betteralign (Make target: betteralign)
Modernize code using gopls modernize (Make target: modernize)
Files:
client/client_test.go
🧬 Code graph analysis (1)
client/client_test.go (2)
client/request.go (1)
AcquireRequest(983-989)client/client.go (1)
Config(641-655)
🔇 Additional comments (4)
client/client_test.go (4)
2091-2098: LGTM! String body handling test is correct.The renamed test clearly validates that string bodies are converted to
[]byte, aligning with the PR objective to support raw string bodies without JSON-encoding.
2100-2107: LGTM! Byte body handling test is well-structured.This test correctly validates that
[]bytebodies are preserved as-is without conversion, supporting the raw byte body feature.
2109-2120: LGTM! JSON body test validates struct storage.The test correctly verifies that struct bodies are stored as-is in the request, to be JSON-marshaled later when the request is sent. This supports the distinction between raw bodies (string/[]byte) and JSON-serializable bodies.
2122-2133: LGTM! Map body test provides good coverage.This test correctly validates that map bodies are preserved as-is, completing the test coverage for different body types (string, []byte, struct, and map).
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #3820 +/- ##
==========================================
- Coverage 92.18% 92.17% -0.02%
==========================================
Files 115 115
Lines 9662 9668 +6
==========================================
+ Hits 8907 8911 +4
- Misses 484 485 +1
- Partials 271 272 +1
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
…ter error handling
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (4)
client/client_test.go (4)
2102-2109: Consider edge case tests for byte slice bodies.The test correctly verifies that
[]bytebodies are stored as-is. Consider adding tests for edge cases:
nilbyte slice:Config{Body: []byte(nil)}- Empty byte slice:
Config{Body: []byte{}}These edge cases ensure robust handling of boundary conditions.
2126-2137: Test verifies storage but not JSON marshaling for maps.Similar to the struct test, this verifies that map bodies are stored internally but doesn't verify the actual JSON marshaling and sending behavior. The complete flow should be tested to ensure maps are correctly marshaled to JSON and sent in HTTP requests.
2091-2137: Add tests verifying mutual exclusivity of Body, FormData, and File.The implementation correctly enforces priority through early returns (Body returns at line 713, preventing FormData/File processing). However, the current test suite only verifies individual body types—not that setting Body actually prevents FormData and File from being processed.
Add integration tests for mutual exclusivity:
- Body set with FormData present → Body used, FormData ignored
- Body set with File present → Body used, File ignored
- FormData set with File present → FormData used, File ignored
This ensures the documented priority ("Body > FormData > File") is testable and prevents regressions.
2091-2100: Test is correct; no changes needed. Consider adding edge case tests as optional enhancement.The test properly verifies that string bodies are converted to
[]byte. Verification confirms that the implementation callsSetRawBody([]byte(v))for string bodies, and the test correctly validates this by checking the resultingreq.bodyvalue.Optional improvement: Consider adding edge case tests for:
- Empty string:
""- Unicode/multibyte characters:
"测试🎉"- Large strings (if performance is a concern)
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
client/client_test.go(1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.go
📄 CodeRabbit inference engine (AGENTS.md)
**/*.go: Apply formatting using gofumpt (Make target: format)
Optimize struct field alignment using betteralign (Make target: betteralign)
Modernize code using gopls modernize (Make target: modernize)
Files:
client/client_test.go
🧬 Code graph analysis (1)
client/client_test.go (2)
client/request.go (1)
AcquireRequest(983-989)client/client.go (1)
Config(641-655)
🔇 Additional comments (1)
client/client_test.go (1)
2111-2124: Test correctly validates unit-level responsibility ofsetConfigToRequest; no changes needed.This test appropriately verifies that
setConfigToRequeststores struct bodies by callingSetJSON, which sets the internal state (req.bodyandreq.bodyType). JSON marshaling is handled separately by theparserRequestBodyhook inhooks.go(lines 200-207), which executes during request sending—not during configuration. Integration tests that verify end-to-end JSON marshaling already exist inrequest_test.go(e.g., lines 1193-1198). The test structure aligns with other body-type tests ("set body string", "set body byte", etc.) and fulfills its unit-testing purpose.Likely an incorrect or invalid review comment.
|
Congrats on merging your first pull request! 🎉 We here at Fiber are proud of you! If you need help or want to chat with us, join us on Discord https://gofiber.io/discord |
Summary