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

huangapple go评论73阅读模式
英文:

Changing default header for JSON data in Gin

问题

我注意到使用Gin返回响应时,会自动创建以下标头:

application/json; charset=utf-8

是否有可能以某种方式修改标头,只返回

application/json

我更喜欢采用这种方法,而不是在分号处拆分字符串。

英文:

I've noticed that using Gin to return a response like this:

c.JSON(http.StatusOK, jsonData)

automatically creates the following header:

application/json; charset=utf-8

Is it possible to modify the header somehow to just return

application/json

I'd rather take this approach than splitting the string at the ;

答案1

得分: 9

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

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

func JSON(c *gin.Context, code int, obj interface{}) {
    c.Header("Content-Type", "application/json")
    c.JSON(code, obj)
}

// ...

JSON(c, http.StatusOK, jsonData)
英文:
  1. Modify the source code to remove the ; charset=utf-8 string, or

  2. Have a wrapper function which manually sets Content-Type before the gin.Context.JSON call:

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

答案2

得分: 0

你可以像这样在请求中添加新的头部:

c.Request.Header.Add("x-request-id", requestID)
英文:

You can add new headers in the request like this :

c.Request.Header.Add("x-request-id", requestID)

huangapple
  • 本文由 发表于 2015年10月1日 22:37:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/32890331.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定