Gin-Gonic Content-Type 限制

Gin-Gonic Content-Type restriction

有一个用golang写的服务,使用gin-gonic框架。

我只想支持 application/json 作为 mime-type,如果它始终采用 UTF-8 格式,那就太好了。如果服务的业务逻辑将以不同的编码获取值,则它可能会中断。

编写一个自定义中间件来检查 Content-Type header 是否具有值 "application/json; charset=utf-8" 和 return 一些 4xx 状态以防它不是一个好主意?

更新: 刚发现 ctx.ContentType() 不是 return charset header 的一部分。有办法得到吗?

没有什么能阻止您直接查看 "Content-Type" http header,调到 ctx.Request.Header.Get("Content-Type")

帮助程序 ContentType 方法由 gin-gonic 提供,特别适用于查询输入数据的 "unadulterated" mime 类型的常见情况。