-
Notifications
You must be signed in to change notification settings - Fork 18.4k
Description
Proposal Details
Abstract
This proposal suggests adding a new method, WriteFile
, to the mime/multipart.Writer
type in the Go standard library. The WriteFile
method will simplify the process of adding file content to multipart forms directly from an io.Reader
, enhancing the package's capability to handle file uploads efficiently, especially for large files or files sourced from streams.
Background
The current mime/multipart.Writer
API provides methods like CreateFormFile
and CreateFormField
for adding files and fields to multipart forms, which are widely used in HTTP client and server implementations for file uploads. However, after calling CreateFormFile
, developers must manually copy the file content into the returned writer, which can be cumbersome.
Proposal
I propose adding a new method to the mime/multipart.Writer
type:
func (w *Writer) WriteFile(fieldname, filename string, src io.Reader) error {
p, err := w.CreateFormFile(fieldname, filename)
if err != nil {
return err
}
_, err = io.Copy(p, src)
return err
}
This method will perform the following tasks:
- Create a form file part with the provided field name and filename.
- Stream data from the provided io.Reader to the form file part.
- Simplify adding file content to multipart forms, especially when the content is already available as an io.Reader (e.g., file streams, network data).
Rationale
-
Ease of Use: The WriteFile method abstracts away the boilerplate code associated with setting up form file parts and copying data, leading to cleaner and more concise client code.
-
Efficiency: It's particularly beneficial for streaming large files or data from network sources, as it doesn't require loading the entire file content into memory.
-
Consistency with Existing APIs: While the
mime/multipart
package already providesWriteField
for simple text fields, there is no equivalent convenience method for files.WriteFile
fills this gap and aligns with the existing API design.
Compatibility
This change is fully backward-compatible. It introduces a new method to the existing mime/multipart.Writer type without modifying any existing functionality. It will not affect existing codebases using the mime/multipart package.
Conclusion
Adding WriteFile
to mime/multipart.Writer will enhance the Go standard library's ability to handle file uploads in a more efficient and user-friendly manner. This addition is a natural extension of the existing multipart API and will be beneficial for a wide range of applications that rely on file uploads, particularly those dealing with large or streamed files.
Metadata
Metadata
Assignees
Labels
Type
Projects
Status