Build Multipart Form Request Bodies
Compose multipart/form-data bodies with mime/multipart, attach file parts, and parse the encoded payload back to verify fields and contents.
Code
package main
import (
"bytes"
"fmt"
"io"
"mime/multipart"
"net/http"
)
func main() {
// Build multipart form request bodies field by field
var body bytes.Buffer
writer := multipart.NewWriter(&body)
// 普通字段
if err := writer.WriteField("owner", "ada"); err != nil {
fmt.Println("field failed:", err)
return
}
// 文件字段:Content-Disposition 与文件名由 CreateFormFile 写入
part, err := writer.CreateFormFile("avatar", "avatar.txt")
if err != nil {
fmt.Println("file part failed:", err)
return
}
if _, err := io.WriteString(part, "fake image bytes"); err != nil {
fmt.Println("write failed:", err)
return
}
if err := writer.Close(); err != nil { // 写入结束边界
fmt.Println("close failed:", err)
return
}
req, err := http.NewRequest(http.MethodPost, "https://example.test/upload", &body)
if err != nil {
fmt.Println("request failed:", err)
return
}
req.Header.Set("Content-Type", writer.FormDataContentType())
fmt.Println("content type:", req.Header.Get("Content-Type"))
// 解析回来核对:字段与文件都按名字索引
reader := multipart.NewReader(bytes.NewReader(body.Bytes()), writer.Boundary())
form, err := reader.ReadForm(1 << 20)
if err != nil {
fmt.Println("read form failed:", err)
return
}
fmt.Println("owner:", form.Value["owner"][0])
for name, files := range form.File {
fmt.Println("file field:", name, "name:", files[0].Filename)
}
}How it works
Build Multipart Form Request Bodies comes down to the function main.
The cycling part of this snippet is for name, files := range form.File. Nothing falls through silently — 6 checkpoints test err != nil on the way through.
Using it
The run emits 9 labeled sections — field failed:, file part failed:, write failed:, close failed:, request failed:, content type:, read form failed:, owner:, file field: — one per step.
Key statements
for name, files := range form.File {
fmt.Println("file field:", name, "name:", files[0].Filename)
}
if err != nil {
fmt.Println("file part failed:", err)
return
}
if err != nil {
fmt.Println("request failed:", err)
return
}
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.HTTP Request Builder & cURLBuild HTTP requests with method, URL, headers, and body, then generate the equivalent cURL command. Supports GET, POST, PUT, DELETE, and PATCH with custom headers.Accept Header ParserParse an Accept header into media ranges with their quality values and specificity, sorted by preference for content negotiation debugging.Basic & Bearer Auth Header ToolEncode and decode HTTP Authorization Basic and Bearer headers locally with UTF-8 Base64 validation and automatic JWT claim and expiry inspection.
FAQ
- What does Build Multipart Form Request Bodies print when run?
- No setup needed: run the file and look for labeled lines like `field failed:`, `file part failed:`, `write failed:` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.