Skip to content

feat(http): add file upload handling with size validation#22

Merged
pcfreak30 merged 1 commit intodevelopfrom
updates
Jul 8, 2025
Merged

feat(http): add file upload handling with size validation#22
pcfreak30 merged 1 commit intodevelopfrom
updates

Conversation

@pcfreak30
Copy link
Copy Markdown
Member

@pcfreak30 pcfreak30 commented Jul 8, 2025

  • Introduces FileUploadResult struct to hold uploaded file metadata
  • Implements PrepareFileUpload method to handle both multipart and raw file uploads
  • Supports seekable and non-seekable sources
  • Validates against maximum upload size
  • Adds comprehensive tests for multipart, raw body, and size limit scenarios

Summary by CodeRabbit

  • New Features

    • Added support for handling file uploads from HTTP requests, including both multipart form and raw binary uploads, with size limit enforcement.
  • Tests

    • Introduced tests to verify correct handling of multipart file uploads, raw body uploads, and enforcement of file size limits.

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Jul 8, 2025

Walkthrough

A new method, PrepareFileUpload, was added to the RequestContext type to handle file uploads from HTTP requests, supporting both multipart and raw binary uploads. Supporting types and helpers were introduced. Corresponding tests were implemented to verify multipart uploads, raw uploads, and size limit enforcement. The go.mod file was updated to remove several dependencies and reduce overall dependencies.

Changes

File(s) Change Summary
http.go Added PrepareFileUpload method to RequestContext, new FileUploadResult struct, and readSeekNopCloser helper type.
http_test.go Added tests for multipart upload, raw body upload, and size limit enforcement for file uploads.
go.mod Removed multiple direct and indirect dependencies, reducing and replacing YAML, JSON, and OpenAPI-related packages.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant RequestContext
    participant Server

    Client->>Server: Send HTTP request (multipart or raw body)
    Server->>RequestContext: Call PrepareFileUpload(maxUploadSize)
    alt Multipart form
        RequestContext->>RequestContext: Parse multipart form
        RequestContext->>RequestContext: Retrieve "file" part
        alt File is seekable
            RequestContext->>Server: Return FileUploadResult with file
        else Not seekable
            RequestContext->>RequestContext: Read file into memory
            RequestContext->>Server: Return FileUploadResult with wrapped reader
        end
    else Raw body
        RequestContext->>RequestContext: Read body into memory
        RequestContext->>Server: Return FileUploadResult with wrapped reader
    end
Loading

Poem

In the garden of code where the uploads grow,
A bunny prepared files, both swift and slow.
Multipart or raw, the bytes hop in,
With limits enforced, and tests to begin.
Now every upload, big or small,
Is handled with care—no trouble at all! 🐇✨


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between db27479 and 43669b1.

📒 Files selected for processing (3)
  • go.mod (1 hunks)
  • http.go (1 hunks)
  • http_test.go (2 hunks)
✅ Files skipped from review due to trivial changes (1)
  • go.mod
🚧 Files skipped from review as they are similar to previous changes (2)
  • http.go
  • http_test.go
✨ Finishing Touches
  • 📝 Generate Docstrings

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
🪧 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @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
Copy Markdown

@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 (1)
http_test.go (1)

442-456: Expand test coverage for multipart size limit enforcement.

The current test only covers raw body size limit enforcement. Consider adding a test case for multipart uploads that exceed the size limit to ensure comprehensive coverage of the PrepareFileUpload method.

Add a multipart size limit test:

func TestPrepareFileUpload_MultipartSizeLimit(t *testing.T) {
    body := &bytes.Buffer{}
    writer := multipart.NewWriter(body)
    part, err := writer.CreateFormFile("file", "large.txt")
    if err != nil {
        t.Fatal(err)
    }
    
    // Create content exceeding limit
    largeContent := make([]byte, 1025) // 1KB + 1 byte
    _, err = part.Write(largeContent)
    if err != nil {
        t.Fatal(err)
    }
    writer.Close()

    req := httptest.NewRequest("POST", "/upload", body)
    req.Header.Set("Content-Type", writer.FormDataContentType())
    w := httptest.NewRecorder()
    e := echo.New()
    r := Context(e.NewContext(req, w))

    _, err = r.PrepareFileUpload(1024) // 1KB limit
    if err == nil {
        t.Fatal("Expected error for exceeding multipart size limit")
    }
    if !strings.Contains(err.Error(), "failed to parse multipart form") {
        t.Errorf("Expected multipart parsing error, got: %v", err)
    }
}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between bd1bb58 and db27479.

📒 Files selected for processing (2)
  • http.go (1 hunks)
  • http_test.go (2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
http_test.go (1)
context.go (1)
  • Context (17-30)
http.go (1)
context.go (1)
  • RequestContext (11-13)
🔇 Additional comments (6)
http.go (3)

4-4: LGTM: Required imports added for file handling.

The new imports support the file upload functionality - bytes for in-memory buffering and io for file operations.

Also applies to: 7-7


15-20: LGTM: Well-structured result type.

The FileUploadResult struct provides a clean interface with appropriate types for file handling operations.


86-93: LGTM: Proper seekable wrapper implementation.

The readSeekNopCloser helper correctly implements the required interface by embedding *bytes.Reader and providing a no-op Close() method.

http_test.go (3)

8-9: LGTM: Required imports for file upload testing.

The new imports support multipart form testing and general I/O operations needed for the test scenarios.


375-414: LGTM: Comprehensive multipart upload test.

The test properly constructs a multipart form, verifies all aspects of the upload result (filename, size, content), and includes proper cleanup with defer.


416-440: LGTM: Solid raw body upload test.

The test correctly verifies raw body upload functionality, checking both size and content accuracy.

Comment thread http.go
* Introduces FileUploadResult struct to hold uploaded file metadata
* Implements PrepareFileUpload method to handle both multipart and raw file uploads
* Supports seekable and non-seekable sources
* Validates against maximum upload size
* Adds comprehensive tests for multipart, raw body, and size limit scenarios
@pcfreak30 pcfreak30 merged commit 6dae0fc into develop Jul 8, 2025
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant