multipart.NewWriter, SetBoundary, NewReader, NextPart, and Close
func NewWriter(w io.Writer) *Writer
func (w *Writer) SetBoundary(boundary string) error
func (w *Writer) CreateFormField(fieldname string) (io.Writer, error)
func (w *Writer) CreateFormFile(fieldname, filename string) (io.Writer, error)
func (w *Writer) FormDataContentType() string
func (w *Writer) Close() error
func NewReader(r io.Reader, boundary string) *Reader
func (r *Reader) NextPart() (*Part, error)
func (p *Part) FormName() string
func (p *Part) FileName() stringWrite two parts with a fixed boundary, close the writer, then read both parts and close each one.
| Parameter | Description |
|---|---|
boundary | Set before any part is created. The example uses TestBoundary so the text is deterministic. Production writers can keep the random default. |
fieldname, filename | The form name, and the file name for CreateFormFile. note.txt is sample data, not a path that is opened. |
Returns: NextPart returns *Part and an error. After the last part, the error is io.EOF. Close on the Writer and on each Part returns an error if flushing fails.
Errors
io.EOF— Normal end of the part list after a well-formed, closed message.error— SetBoundary fails if a part has already been written or if the boundary is invalid. NextPart fails on a truncated message, including one whose Writer was never closed.
- The file part is written in memory. No local file is opened.
package main
import (
"bytes"
"fmt"
"io"
"mime"
"mime/multipart"
)
func main() {
var buf bytes.Buffer
w := multipart.NewWriter(&buf)
fmt.Println("boundary", w.SetBoundary("TestBoundary"))
field, err := w.CreateFormField("title")
fmt.Println("field", err)
_, _ = field.Write([]byte("hello"))
file, err := w.CreateFormFile("file", "note.txt")
fmt.Println("file", err)
_, _ = file.Write([]byte("abc"))
fmt.Println("close_writer", w.Close())
_, params, err := mime.ParseMediaType(w.FormDataContentType())
fmt.Println("parsed_boundary", err, params["boundary"])
r := multipart.NewReader(&buf, w.Boundary())
for {
part, err := r.NextPart()
if err == io.EOF {
fmt.Println("eof")
break
}
fmt.Println("next", err)
data, _ := io.ReadAll(part)
fmt.Printf("name=%s file=%s data=%s\n", part.FormName(), part.FileName(), data)
fmt.Println("close_part", part.Close())
}
}Expected output
boundary <nil>
field <nil>
file <nil>
close_writer <nil>
parsed_boundary <nil> TestBoundary
next <nil>
name=title file= data=hello
close_part <nil>
next <nil>
name=file file=note.txt data=abc
close_part <nil>
eofRelated: mime.ParseMediaType, io