Parse Media Types With mime.ParseMediaType

Turn Content-Type style strings into a canonical type plus a parameter map with mime.ParseMediaType, so malformed values fail instead of being guessed.

GoConfig Management

Code

gosnippet
31 lines
package main

import (
	"fmt"
	"mime"
)

func main() {
	inputs := []string{
		"text/html; charset=utf-8",
		`application/json; charset="utf-8"; version=2`,
		"multipart/form-data; boundary=a1b2",
		"text/plain; charset",
	}

	for _, raw := range inputs {
		mediaType, params, err := mime.ParseMediaType(raw)
		if err != nil {
			// 参数缺 =、引号不闭合等都在这条分支返回错误
			fmt.Printf("%-52q rejected: %v\n", raw, err)
			continue
		}
		fmt.Printf("%-52q -> %s %v\n", raw, mediaType, params)
	}

	// FormatMediaType 反向拼装:媒体类型小写、参数按键排序,适合做缓存键
	fmt.Println(mime.FormatMediaType("Application/JSON", map[string]string{
		"version": "2",
		"charset": "utf-8",
	}))
}

A closer look

The parts that move are inside the function main.

The file repeats itself only inside for _, raw := range inputs. Error handling is inline: 1 place test err != nil and branch immediately.

Points of care

  • Nothing to install: every API here comes with the runtime itself.

Applying it

The main signature reads func main()

Statements that matter

for _, raw := range inputs {
mediaType, params, err := mime.ParseMediaType(raw)
if err != nil {
// 参数缺 =、引号不闭合等都在这条分支返回错误
fmt.Printf("%-52q rejected: %v\n", raw, err)
continue
}
fmt.Printf("%-52q -> %s %v\n", raw, mediaType, params)
}

Interactive Tools for This Topic

FAQ

How do you run Parse Media Types With mime.ParseMediaType?
The file is self-contained: run it directly, no dependencies to install beforehand.