0
votes

I am using Gin-gonic to create an API. All requests whether thats a GET or a POST will be in JSON.

I have an API call which works fine but I have to add these headers through with the cURL -H "Accept: application/json" -H "Content-type: application/json" otherwise the POST does not work as expected.

I tried adding this function as middleware but although it changed the headers slightly it still does not work as expected

func CORSMiddleware() gin.HandlerFunc {
    return func(c *gin.Context) {

        c.Writer.Header().Set("Content-Type", "application/json")
        c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
        c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")

    }
}

Headers when it works (with added header in cURL): Accept: application/json Content-type: application/json

Header when it doesn't work (no header in cURL): Accept: */* Content-Type: application/x-www-form-urlencoded

Is there any way to force the headers rather than asking the user to supply them?

1
As I know method Set(key, value) just sets value for existing key. Method Add(key, value) adds new pair key-value or appends value if key exists.Alex Kroll
@AlexKroll not really. HTTP header allow multiple values for one key, so Add(key, value) do append value to existing key.Jiang YD
@JiangYD and what I was wrong? src/net/http/header.go // Add adds the key, value pair to the header. // It appends to any existing values associated with key. func (h Header) Add(key, value string) { textproto.MIMEHeader(h).Add(key, value) }Alex Kroll
@AlexKroll yes my mistake. anyhow the question not relate to duplicate key.Jiang YD

1 Answers

1
votes

Content-type is a import HTTP header letting server decide how to parse the HTTP body.

Is there any way to force the headers rather than asking the user to supply them?

Hard to say Yes or No, it is depends on your 'user'. For curl, it can not guess the HTTP body format and set Content-Type to 'applicatoin/json' automatically, so you need specify Content-Type. For others like jQuery, programmer can set the dataType in post jQuery.post( url [, data ] [, success ] [, dataType ] ) link