Golang gin gonic内容类型没有设置为带有c.JSON的application / json

时间:2016-12-12 20:33:44

标签: json go

根据official documentationgin-gonic的c.JSON应将响应标头设置为application/json,但当我从Postman调用我的API时,响应标头为设置为text/plain; charset=utf-8

我不明白我缺少什么,不知道吗?

Doc:

  

func 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 Header

type Credentials struct {
    Email         string        `json:"email" binding:"required"`
    Password      string        `json:"password" binding:"required"`
}

3 个答案:

答案 0 :(得分:2)

查看源代码后,如果已设置Content-Type标题,它似乎不会写入。{/ p>

c.JSON调用this function调用以下代码:

func writeContentType(w http.ResponseWriter, value []string) {
    header := w.Header()
    if val := header["Content-Type"]; len(val) == 0 {
        header["Content-Type"] = value
    }
}

因此,您的Content-Type必须设置在其他地方。

答案 1 :(得分:1)

如果您希望所有请求都是JSON,请添加一个中间件。

func JSONMiddleware() gin.HandlerFunc {
    return func(c *gin.Context) {
        c.Writer.Header().Set("Content-Type", "application/json")
        c.Next()
    }
}

在路由器上添加

router.Use(JSONMiddleware())

答案 2 :(得分:-1)

使用 c.ShouldBindJSON(&credentials) 而不是 c.BindJSON

<块引用>

Gin README.md - Model binding and validation

这些方法在幕后使用 MustBindWith。如果有绑定 错误,请求被中止 c.AbortWithError(400, 错误).SetType(ErrorTypeBind)。这将响应状态代码设置为 400 并且 Content-Type 标头设置为 text/plain;字符集=utf-8。

相关问题