更改 Gin 中 JSON 数据的默认标头

tom*_*456 4 go go-gin

我注意到使用 Gin 返回这样的响应:

c.JSON(http.StatusOK, jsonData)
Run Code Online (Sandbox Code Playgroud)

自动创建以下标头:

application/json; charset=utf-8
Run Code Online (Sandbox Code Playgroud)

是否可以以某种方式修改标头以返回

application/json
Run Code Online (Sandbox Code Playgroud)

我宁愿采用这种方法而不是在;

小智 9

  1. 修改源代码以删除该; charset=utf-8字符串,或者

  2. Content-Type有一个在调用之前手动设置的包装函数gin.Context.JSON

    func JSON(c *gin.Context, code int, obj interface{}) {
        c.Header("Content-Type", "application/json")
        c.JSON(code, obj)
    }
    
    // ...
    
    JSON(c, http.StatusOK, jsonData)
    
    Run Code Online (Sandbox Code Playgroud)