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

bind: add support for multipart file binding #3309

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

Conversation

efectn
Copy link
Member

@efectn efectn commented Feb 13, 2025

Description

This PR adds support for multipart file binding when content type is multipart/form-data
Fixes #2002

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.
  • Changelog/What's New: Include a summary of the additions for the upcoming release notes.
  • Examples: Provide examples demonstrating the new features or changes in action.

Type of change

  • Enhancement (improvement to existing features and functionality)

Checklist

  • Followed the inspiration of the Express.js framework for new functionalities, making them similar in usage.
  • Conducted a self-review of the code and provided comments for complex or critical parts.
  • 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.
  • Verified that any new dependencies are essential and have been agreed upon by the maintainers/community.
  • 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 added this to the v3 milestone Feb 13, 2025
@efectn efectn requested a review from a team as a code owner February 13, 2025 14:29
@efectn efectn requested review from gaby, sixcolors and ReneWerner87 and removed request for a team February 13, 2025 14:29
Copy link
Contributor

coderabbitai bot commented Feb 13, 2025

Warning

Rate limit exceeded

@efectn has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 24 minutes and 21 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between ec7c89a and a420917.

📒 Files selected for processing (3)
  • binder/form_test.go (5 hunks)
  • binder/mapping.go (5 hunks)
  • docs/api/bind.md (1 hunks)

Walkthrough

The changes extend the binder’s functionality to support multipart file uploads. The bindMultipart method now collects file headers and passes them along to the parsing functions. Test cases are updated with new file-related struct fields to verify file upload binding. Additionally, the mapping functions are modified to accept file data, and the documentation is enhanced with binding examples and corresponding curl commands. Broader API documentation also reflects these updates within the Fiber framework v3 release notes.

Changes

File(s) Change Summary
binder/form.go,
binder/form_test.go,
binder/mapping.go
Enhanced multipart/form-data binding to support file uploads by introducing file header handling, iterating over file parts, and updating function signatures and parsing logic.
docs/api/bind.md Updated documentation to include examples of binding multipart file uploads, with sample struct definitions and curl commands for testing file uploads.
docs/whats_new.md Revised release notes for v3, detailing changes in method signatures, route handling, and the new support for multipart file binding alongside other API improvements.

Sequence Diagram(s)

sequenceDiagram
    participant C as Client
    participant F as FormBinding.bindMultipart
    participant P as parse/parseToStruct
    participant D as Decoder

    C->>F: Submit multipart/form-data with files
    F->>F: Iterate over form fields and file headers
    F->>P: Call parse with regular data and file headers
    P->>D: Decode both form fields and file uploads
    D-->>P: Return bound data structure
    P-->>F: Provide parsed result
    F-->>C: Respond with binding result
Loading

Possibly related PRs

Suggested labels

✏️ Feature, v3

Suggested reviewers

  • sixcolors
  • gaby
  • ReneWerner87

Poem

I’m a rabbit coding with delight,
Files hop in with a joyous bite.
New headers bound in a rhythmic dance,
Each multipart upload gets its chance.
With sniffs and hops, bugs take flight,
Celebrating code in the moonlight!


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. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (2)
binder/form_test.go (1)

101-101: Field alignment issue (88 pointer bytes → 80).
Reordering fields for better alignment may reduce memory usage:

-type User struct {
-	Name    string                  `form:"name"`
-	Names   []string                `form:"names"`
-	Posts   []Post                  `form:"posts"`
-	Age     int                     `form:"age"`
-	Avatar  *multipart.FileHeader   `form:"avatar"`
-	Avatars []*multipart.FileHeader `form:"avatars"`
+type User struct {
+	Age     int                     `form:"age"`
+	Name    string                  `form:"name"`
+	Names   []string                `form:"names"`
+	Posts   []Post                  `form:"posts"`
+	Avatar  *multipart.FileHeader   `form:"avatar"`
+	Avatars []*multipart.FileHeader `form:"avatars"`
}
🧰 Tools
🪛 golangci-lint (1.62.2)

101-101: fieldalignment: struct with 88 pointer bytes could be 80

(govet)

🪛 GitHub Check: lint

[failure] 101-101:
fieldalignment: struct with 88 pointer bytes could be 80 (govet)

🪛 GitHub Actions: golangci-lint

[error] 101-101: fieldalignment: struct with 88 pointer bytes could be 80 (govet)

docs/api/bind.md (1)

154-155: Remove extra blank line.

-
🧰 Tools
🪛 markdownlint-cli2 (0.17.2)

155-155: Multiple consecutive blank lines
Expected: 1; Actual: 2

(MD012, no-multiple-blanks)

🪛 GitHub Check: markdownlint

[failure] 155-155: Multiple consecutive blank lines
docs/api/bind.md:155 MD012/no-multiple-blanks Multiple consecutive blank lines [Expected: 1; Actual: 2] https://github.com/DavidAnson/markdownlint/blob/v0.37.4/doc/md012.md

🪛 GitHub Actions: markdownlint

[error] 155-155: Multiple consecutive blank lines [Expected: 1; Actual: 2]

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b0bc32b and ec7c89a.

⛔ Files ignored due to path filters (2)
  • go.mod is excluded by !**/*.mod
  • go.sum is excluded by !**/*.sum, !**/*.sum
📒 Files selected for processing (5)
  • binder/form.go (2 hunks)
  • binder/form_test.go (5 hunks)
  • binder/mapping.go (5 hunks)
  • docs/api/bind.md (1 hunks)
  • docs/whats_new.md (1 hunks)
🧰 Additional context used
🪛 GitHub Actions: golangci-lint
binder/form_test.go

[error] 101-101: fieldalignment: struct with 88 pointer bytes could be 80 (govet)

🪛 LanguageTool
docs/api/bind.md

[uncategorized] ~124-~124: Possible missing article found.
Context: ...t:3000 ``` :::info If you need to bind multipart file, you can use `*multipart.FileHeade...

(AI_HYDRA_LEO_MISSING_A)


[style] ~124-~124: Three successive sentences begin with the same word. Consider rewording the sentence or use a thesaurus to find a synonym.
Context: ...eHeader, *[]*multipart.FileHeaderor[]*multipart.FileHeader` as a field type. ::: ```go title="Exa...

(ENGLISH_WORD_REPEAT_BEGINNING_RULE)

docs/whats_new.md

[style] ~490-~490: Three successive sentences begin with the same word. Consider rewording the sentence or use a thesaurus to find a synonym.
Context: ...eader, *[]*multipart.FileHeader, and []*multipart.FileHeader` field types.

Examp...

(ENGLISH_WORD_REPEAT_BEGINNING_RULE)

🪛 markdownlint-cli2 (0.17.2)
docs/api/bind.md

155-155: Multiple consecutive blank lines
Expected: 1; Actual: 2

(MD012, no-multiple-blanks)

🪛 GitHub Check: markdownlint
docs/api/bind.md

[failure] 155-155: Multiple consecutive blank lines
docs/api/bind.md:155 MD012/no-multiple-blanks Multiple consecutive blank lines [Expected: 1; Actual: 2] https://github.com/DavidAnson/markdownlint/blob/v0.37.4/doc/md012.md

🪛 GitHub Actions: markdownlint
docs/api/bind.md

[error] 155-155: Multiple consecutive blank lines [Expected: 1; Actual: 2]

🪛 golangci-lint (1.62.2)
binder/mapping.go

265-265: Error return value is not checked

(errcheck)


265-265: type assertion must be checked

(forcetypeassert)


268-268: Error return value is not checked

(errcheck)


268-268: type assertion must be checked

(forcetypeassert)


272-272: type assertion must be checked

(forcetypeassert)


272-272: Error return value is not checked

(errcheck)

🪛 GitHub Check: lint
binder/mapping.go

[failure] 265-265:
Error return value is not checked (errcheck)


[failure] 265-265:
type assertion must be checked (forcetypeassert)


[failure] 268-268:
Error return value is not checked (errcheck)


[failure] 268-268:
type assertion must be checked (forcetypeassert)


[failure] 272-272:
type assertion must be checked (forcetypeassert)


[failure] 272-272:
Error return value is not checked (errcheck)

⏰ Context from checks skipped due to timeout of 90000ms (5)
  • GitHub Check: unit (1.23.x, macos-13)
  • GitHub Check: unit (1.23.x, macos-latest)
  • GitHub Check: unit (1.23.x, windows-latest)
  • GitHub Check: repeated
  • GitHub Check: Compare
🔇 Additional comments (18)
binder/mapping.go (7)

6-6: Import addition looks good.
No issues with adding "mime/multipart" for handling file headers.


73-73: Good approach adding files ...map[string][]*multipart.FileHeader.
This parameter extension cleanly supports file data alongside string data.


87-87: Consistent call to parseToStruct.
Passing the additional files parameter ensures that file data is handled in one place.


91-91: Extended signature for parseToStruct.
This aligns well with the new files parameter, allowing the schema decoder to handle file headers.


99-99: Error handling is correct.
Decoding logic properly wraps and returns errors.


254-254: Signature refactoring to func formatBindData[T, K any].
Expanding generic types makes sense for differentiating between text and file-based data.


268-268: Repeat of unchecked type assertion.
Same concern applies when passing val to assignBindData.

🧰 Tools
🪛 golangci-lint (1.62.2)

268-268: Error return value is not checked

(errcheck)


268-268: type assertion must be checked

(forcetypeassert)

🪛 GitHub Check: lint

[failure] 268-268:
Error return value is not checked (errcheck)


[failure] 268-268:
type assertion must be checked (forcetypeassert)

binder/form.go (2)

4-5: Importing mime/multipart is correct for file-bound data.
No issues here.


64-72: Efficient approach to separate file data from form data.
Collecting file headers into files then passing them to parse is clean. Consider large file scenarios, but for typical usage, this is fine.

binder/form_test.go (5)

5-5: Importing io is appropriate for reading uploaded files.
No concerns here.


102-107: Struct extension for file fields.
Allowing single and multiple file headers covers common use cases.


124-141: Writing multiple files for multipart testing.
This is a thorough test setup for verifying single and multiple file fields.


151-151: Binding call ensures robust end-to-end coverage.
Good to see the real request object used in tests.


164-195: Detailed validation of file attachments.
Verifying filename, content type, and file contents is essential. This test comprehensively checks the new functionality.

docs/api/bind.md (3)

123-125: LGTM! Clear and concise info block.

The info block effectively communicates the supported field types for multipart file binding.

🧰 Tools
🪛 LanguageTool

[uncategorized] ~124-~124: Possible missing article found.
Context: ...t:3000 ``` :::info If you need to bind multipart file, you can use `*multipart.FileHeade...

(AI_HYDRA_LEO_MISSING_A)


[style] ~124-~124: Three successive sentences begin with the same word. Consider rewording the sentence or use a thesaurus to find a synonym.
Context: ...eHeader, *[]*multipart.FileHeaderor[]*multipart.FileHeader` as a field type. ::: ```go title="Exa...

(ENGLISH_WORD_REPEAT_BEGINNING_RULE)


127-147: LGTM! Well-structured example code.

The example code clearly demonstrates how to:

  1. Define a struct with a file field
  2. Handle file binding in a route handler
  3. Access the bound file properties

151-153: LGTM! Helpful curl example.

The curl command provides a clear example of how to test the file binding functionality.

docs/whats_new.md (1)

490-490: LGTM! Clear feature documentation.

The entry clearly documents the new multipart file binding support and lists all supported field types.

🧰 Tools
🪛 LanguageTool

[style] ~490-~490: Three successive sentences begin with the same word. Consider rewording the sentence or use a thesaurus to find a synonym.
Context: ...eader, *[]*multipart.FileHeader, and []*multipart.FileHeader` field types.

Examp...

(ENGLISH_WORD_REPEAT_BEGINNING_RULE)

binder/mapping.go Outdated Show resolved Hide resolved
binder/mapping.go Outdated Show resolved Hide resolved
Copy link

codecov bot commented Feb 13, 2025

Codecov Report

Attention: Patch coverage is 56.66667% with 13 lines in your changes missing coverage. Please review.

Project coverage is 84.05%. Comparing base (b0bc32b) to head (a420917).

Files with missing lines Patch % Lines
binder/mapping.go 56.52% 6 Missing and 4 partials ⚠️
binder/form.go 57.14% 2 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #3309      +/-   ##
==========================================
- Coverage   84.15%   84.05%   -0.11%     
==========================================
  Files         116      116              
  Lines       11551    11572      +21     
==========================================
+ Hits         9721     9727       +6     
- Misses       1399     1409      +10     
- Partials      431      436       +5     
Flag Coverage Δ
unittests 84.05% <56.66%> (-0.11%) ⬇️

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

@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: a420917 Previous: b0bc32b Ratio
BenchmarkAppendMsgitem-4_middleware_csrf - MB/s 3186.28 MB/s 1597.59 MB/s 1.99
BenchmarkAppendMsgstorageManager - MB/s 3205.63 MB/s 1583.2 MB/s 2.02
BenchmarkAppendMsgdata - MB/s 3203.57 MB/s 1599.35 MB/s 2.00

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
Status: In Progress
Development

Successfully merging this pull request may close these issues.

🚀 v3 Request: Add Support for *multipart.FileHeader fields to Multipart Binder
1 participant