Skip to content

🐛 fix: Enhance Body handling in setConfigToRequest for better type su…#3820

Merged
ReneWerner87 merged 4 commits intogofiber:mainfrom
K0ng2:main
Oct 26, 2025
Merged

🐛 fix: Enhance Body handling in setConfigToRequest for better type su…#3820
ReneWerner87 merged 4 commits intogofiber:mainfrom
K0ng2:main

Conversation

@K0ng2
Copy link
Contributor

@K0ng2 K0ng2 commented Oct 25, 2025

Summary

  • This change improves flexibility in how request bodies are set when building HTTP requests. Previously, only JSON-serializable bodies were supported. With this update, raw []byte and string bodies can be sent directly without being JSON-encoded.

@K0ng2 K0ng2 requested a review from a team as a code owner October 25, 2025 05:59
@welcome
Copy link

welcome bot commented Oct 25, 2025

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

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Oct 25, 2025

Note

Other AI code review bot(s) detected

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

Walkthrough

setConfigToRequest now preserves multiple Body representations: []byte and string are sent as raw bytes (string -> []byte), while other types are passed to SetJSON. The function returns after processing Body, skipping FormData/File handling when Body is present.

Changes

Cohort / File(s) Summary
Body handling logic
client/client.go
setConfigToRequest now dispatches on cfg.Body type: []byte -> SetRawBody, string -> convert to []byte then SetRawBody, other types -> SetJSON. Early return after handling Body.
Body handling tests
client/client_test.go
Replaced single test with subtests: "set body string", "set body byte", "set body json", "set body map". Tests verify string→[]byte conversion, []byte preservation, and direct preservation of structs/maps (no JSON marshaling in tests).

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

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20–25 minutes

  • Review client/client.go for pointer types, nil handling, and interactions with existing FormData/File code given the early return.
  • Confirm tests in client/client_test.go accurately reflect intended behavior and consider adding pointer/complex-type cases.

Suggested reviewers

  • gaby
  • sixcolors
  • efectn

Poem

🐰 I hopped through code with whiskers bright,
Bytes and strings now sleep just right.
Structs and maps kept as their art,
Each little body plays its part.
A nibble, a hop — a tidy bite!

Pre-merge checks and finishing touches

❌ Failed checks (2 warnings)
Check name Status Explanation Resolution
Description Check ⚠️ Warning The pull request description is largely incomplete compared to the required template structure. While the provided summary is on-topic and clearly explains what changed and the benefit (supporting raw []byte and string bodies without JSON encoding), it lacks most of the structured sections mandated by the template. Specifically, it is missing the "Changes introduced" section with checkboxes for benchmarks, documentation, changelog, migration guide, and API alignment; the "Type of change" section; and the comprehensive "Checklist" section that verifies code review, testing, documentation updates, and performance considerations. These sections are central to the repository's PR process as outlined in the template. Complete the pull request description by filling out all required template sections. Add a "Changes introduced" section documenting whether documentation was updated, changelog entries created, and if API alignment or migration guidance is needed. Include the "Type of change" section indicating whether this is an enhancement, bug fix, or other change type. Finally, add the "Checklist" section and verify all requirements are met, including self-review, unit tests, documentation updates, and performance considerations. Refer to the template structure provided in the repository for proper formatting.
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (1 passed)
Check name Status Explanation
Title Check ✅ Passed The pull request title "🐛 fix: Enhance Body handling in setConfigToRequest for better type su…" is directly related to the main change in the changeset. The summary shows that the primary modification involves enhancing the Body handling in setConfigToRequest to support multiple types ([]byte, string, structs, maps) with appropriate routing logic, which is exactly what the title conveys. While the title includes an emoji, this appears consistent with the repository's commit formatting conventions outlined in the description template, which encourages emoji usage for identifying commit purposes.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello @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 setConfigToRequest function to provide more versatile handling of HTTP request bodies. The change introduces the ability to directly send raw byte arrays and strings as request bodies, in addition to the existing JSON serialization. This enhancement streamlines the process of constructing HTTP requests by accommodating a wider range of body formats, thereby improving the adaptability of the client.

Highlights

  • Enhanced Body Handling: The setConfigToRequest function now supports []byte and string types for request bodies, allowing them to be sent directly without JSON encoding.
  • Increased Flexibility: This update improves the flexibility of setting request bodies, moving beyond the previous limitation of only supporting JSON-serializable bodies.
Using Gemini Code Assist

The 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 /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

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 .gemini/ folder in the base of the repository. Detailed instructions can be found here.

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

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

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.

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

🧹 Nitpick comments (2)
client/client.go (2)

705-712: Add json.RawMessage fast‑path

json.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 bodies

When 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

📥 Commits

Reviewing files that changed from the base of the PR and between 67bbac5 and 9f1c172.

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

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

@gaby gaby requested a review from Copilot October 25, 2025 06:07
Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

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

@gaby
Copy link
Member

gaby commented Oct 25, 2025

@codex Review this implementation:

  • Do the changes make sense?
  • Is there a better approach for this?
  • Which unit-tests would be affected by this change?

Copy link

@chatgpt-codex-connector chatgpt-codex-connector bot left a comment

Choose a reason for hiding this comment

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

💡 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".

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

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

  • nil body value
  • Empty string ""
  • Empty byte slice []byte("") or []byte{}
  • Potentially other types that might be passed (e.g., io.Reader if 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

📥 Commits

Reviewing files that changed from the base of the PR and between 7c9c9e5 and d600c7a.

📒 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 []byte bodies 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
Copy link

codecov bot commented Oct 26, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 92.17%. Comparing base (67bbac5) to head (fa1b454).
⚠️ Report is 1 commits behind head on main.

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     
Flag Coverage Δ
unittests 92.17% <100.00%> (-0.02%) ⬇️

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.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

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

🧹 Nitpick comments (4)
client/client_test.go (4)

2102-2109: Consider edge case tests for byte slice bodies.

The test correctly verifies that []byte bodies are stored as-is. Consider adding tests for edge cases:

  • nil byte 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 calls SetRawBody([]byte(v)) for string bodies, and the test correctly validates this by checking the resulting req.body value.

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

📥 Commits

Reviewing files that changed from the base of the PR and between d600c7a and fa1b454.

📒 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 of setConfigToRequest; no changes needed.

This test appropriately verifies that setConfigToRequest stores struct bodies by calling SetJSON, which sets the internal state (req.body and req.bodyType). JSON marshaling is handled separately by the parserRequestBody hook in hooks.go (lines 200-207), which executes during request sending—not during configuration. Integration tests that verify end-to-end JSON marshaling already exist in request_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.

@ReneWerner87 ReneWerner87 merged commit 262c379 into gofiber:main Oct 26, 2025
15 checks passed
@welcome
Copy link

welcome bot commented Oct 26, 2025

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

@ReneWerner87 ReneWerner87 added this to the v3 milestone Oct 26, 2025
@ReneWerner87 ReneWerner87 added this to v3 Oct 26, 2025
@efectn efectn moved this to Done in v3 Jan 23, 2026
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.

5 participants