使用出色的 Gorilla mux,我可以使用 application/json 作为内容类型来处理 API 请求:
apiRouter := router.PathPrefix("/api").Headers("Content-Type", "application/json").Subrouter()
Run Code Online (Sandbox Code Playgroud)
然而,有些用户喜欢提供的不仅仅是该字符串,即 application/json;字符集=UTF-8。设置此标头值后,处理程序将返回 404。
通过允许 json 和任何字符集规范来处理此问题的最佳方法是什么?
使用正则表达式的其他答案匹配任何字符集或更糟,甚至类似于application/jsonfooo. 如果你想更严格,可以使用匹配器函数:
func matchJSON(r *http.Request, rm *mux.RouteMatch) bool {
ctHdr := r.Header.Get("Content-Type")
contentType, params, err := mime.ParseMediaType(ctHdr)
if err != nil {
return false
}
charset := params["charset"]
return contentType == "application/json" && (charset == "" || strings.EqualFold(charset, "UTF-8"))
}
Run Code Online (Sandbox Code Playgroud)
然后,像这样使用它:
router.PathPrefix("/api").MatcherFunc(matchJSON)
Run Code Online (Sandbox Code Playgroud)