【发布时间】:2017-04-27 19:17:19
【问题描述】:
根据official documentation,gin-gonic的c.JSON应该将响应头设置为application/json,但是当我从Postman调用我的API时,响应头设置为text/plain; charset=utf-8
我不明白我错过了什么,知道吗?
文档:
函数 JSON
JSON 将给定的结构作为 JSON 序列化到响应正文中。它 还将 Content-Type 设置为“application/json”。
这是我的代码示例:
func postLogin(c *gin.Context) {
var credentials DTO.Credentials
if err := c.BindJSON(&credentials); err == nil {
c.JSON(buildResponse(services.CheckUserCredentials(credentials)))
} else {
var apiErrors = DTO.ApiErrors{}
for _, v := range err.(validator.ValidationErrors) {
apiErrors.Errors = append(apiErrors.Errors, DTO.ApiError{Field: v.Field, Message: v.Field + " is " + v.Tag})
}
c.JSON(http.StatusBadRequest, apiErrors)
}
}
编辑
经过调查,log.Println(c.Writer.Header().Get("Content-Type")) 没有打印任何东西,显示内容类型应该是空的。
func writeContentType(w http.ResponseWriter, value []string) {
header := w.Header()
log.Println(header.Get("Content-Type")) // <=========== Nothing happen
if val := header["Content-Type"]; len(val) == 0 {
header["Content-Type"] = value
}
}
我真的不想将c.Writer.Header().Set("Content-Type", "application/json") 添加到我架构中的每条路线...
编辑 2
似乎binding:"required" 破坏了 Content-Type 标头
type Credentials struct {
Email string `json:"email" binding:"required"`
Password string `json:"password" binding:"required"`
}
【问题讨论】: