4

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 ;

Zoyd
  • 3,449
  • 1
  • 18
  • 27
tommyd456
  • 10,443
  • 26
  • 89
  • 163
  • 2
    Why do you have to split the string? You should be able to accept a valid Content-Type header. – JimB Oct 01 '15 at 14:42

2 Answers2

9
  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)
    
  • 1
    I needed to add an `Access-Control-Allow-Origin` header, and this solution worked flawlessly to me (I'm using `c.XML()`, but the concept is pretty much the same). Thanks! – Gwyneth Llewelyn Jun 20 '20 at 14:44
  • 1
    @GwynethLlewelyn You can try this out: [https://github.com/gin-contrib/cors](https://github.com/gin-contrib/cors), a middleware which can add some basic cors headers. – Zhwt Aug 06 '20 at 09:09
  • @Zhwt oh that's even better... thanks so much! I've filed it as a `TODO()` on my code, it's far better to use a much neater library to accomplish the same thing with middleware... – Gwyneth Llewelyn Aug 07 '20 at 14:35
0

You can add new headers in the request like this :

c.Request.Header.Add("x-request-id", requestID)
shivamgoel
  • 53
  • 3
  • 13