duanquan1243
2016-12-12 20:33Golang杜松子酒gonic内容类型未使用c.JSON设置为application / json
According to the official documentation, c.JSON of gin-gonic should set the response header to application/json
, but when I call my API from Postman, the response header is set to text/plain; charset=utf-8
I don't understand what I am missing, any idea ?
Doc :
func JSON
JSON serializes the given struct as JSON into the response body. It also sets the Content-Type as "application/json".
Here is a sample of my code :
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)
}
}
EDIT
After investigation, log.Println(c.Writer.Header().Get("Content-Type")) doesn't print any thing, showing content-type is empty as it should be.
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
}
}
I really don't want to have to add c.Writer.Header().Set("Content-Type", "application/json")
to every route in my architecture...
EDIT 2
It seems like binding:"required"
break the Content-Type Header
type Credentials struct {
Email string `json:"email" binding:"required"`
Password string `json:"password" binding:"required"`
}
- 点赞
- 回答
- 收藏
- 复制链接分享
1条回答
为你推荐
- Golang杜松子酒gonic内容类型未使用c.JSON设置为application / json
- json
- 1个回答
- 如何使Golang杜松子酒与Google App Engine一起使用?
- it技术
- 互联网问答
- IT行业问题
- 计算机技术
- 编程语言问答
- 1个回答
- 杜松子酒/ golang-空需求体
- it技术
- 互联网问答
- IT行业问题
- 计算机技术
- 编程语言问答
- 1个回答