Parse MIME and multipart data
Parse MIME and multipart data
MIME media types describe the representation of a message body. Parameters such as charset and boundary carry extra information. A multipart body uses a boundary to separate parts, each with its own headers. Use mime.ParseMediaType rather than manually splitting on semicolons.
package main
import ( "fmt" "mime")
func main() { t, p, e := mime.ParseMediaType(`Text/Plain; charset="utf-8"`) fmt.Println(t, p["charset"], e == nil) fmt.Println(mime.FormatMediaType("text/plain", map[string]string{"charset": "utf-8"}))}ParseMediaType normalizes the media type and parameter names, while parameter values retain their own semantics. A declared media type is metadata, not proof of content validity. FormatMediaType handles quoting. Check parsing errors and enforce the types your application supports.
Expected output:
text/plain utf-8 truetext/plain; charset=utf-8Bounded form parsing
package main
import ( "bytes" "errors" "fmt" "io" "mime" "mime/multipart")
func form() (string, []byte) { var b bytes.Buffer w := multipart.NewWriter(&b) if e := w.WriteField("label", "blue"); e != nil { panic(e) } if e := w.WriteField("count", "2"); e != nil { panic(e) } if e := w.Close(); e != nil { panic(e) } return w.FormDataContentType(), b.Bytes()}func fields(ct string, b []byte) (map[string]string, error) { typ, p, e := mime.ParseMediaType(ct) if e != nil || typ != "multipart/form-data" || p["boundary"] == "" { return nil, errors.New("bad media type") } if len(b) > 4096 { return nil, errors.New("body too large") } r := multipart.NewReader(bytes.NewReader(b), p["boundary"]) out := map[string]string{} for n := 0; ; n++ { part, e := r.NextPart() if e == io.EOF { return out, nil } if e != nil { return nil, e } if n >= 4 || part.FileName() != "" { return nil, errors.New("unexpected part") } name := part.FormName() if name != "label" && name != "count" { return nil, errors.New("unexpected field") } if _, ok := out[name]; ok { return nil, errors.New("duplicate field") } v, e := io.ReadAll(io.LimitReader(part, 33)) if e != nil || len(v) > 32 { return nil, errors.New("bad field") } if e = part.Close(); e != nil { return nil, e } out[name] = string(v) }}func main() { ct, b := form() v, e := fields(ct, b) fmt.Println(v["label"], v["count"], e == nil)}Writer.Close emits the final boundary. NextPart returns io.EOF after the last part. This fixture permits four small parts at most, rejects files, unknown and duplicate names, and bounds the already-buffered body. In HTTP, bound the stream before buffering (for example MaxBytesReader) and validate required fields afterward. ReadForm may spill files to disk; call RemoveAll when used. Never trust a client filename as a storage path.
Expected output:
blue 2 trueTry it locally
Generate the form, then try parsing with a missing boundary and with the correct content type. Print rejection and the number of parsed fields.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Specialized library 03: Parse MIME and multipart data
Check the lesson objective before moving on.
What separates multipart parts?
Why bound total request bytes before buffering?