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.
Code
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
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.Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.
FAQ
- How do you run Parse Media Types With mime.ParseMediaType?
- The file is self-contained: run it directly, no dependencies to install beforehand.
Report a problem with this exampleOpens a pre-filled issue on GitHub.