英文:
Golang / Gin-gonic : Force POST headers to JSON
问题
我正在使用Gin-gonic创建一个API。所有的请求,无论是GET还是POST,都将以JSON格式进行。
我有一个API调用,它工作得很好,但我必须通过cURL的-H "Accept: application/json" -H "Content-type: application/json"
来添加这些头部,否则POST请求不会按预期工作。
我尝试将这个函数作为中间件添加,但尽管它稍微改变了头部,但仍然不能按预期工作。
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")
}
}
当它工作时的头部(在cURL中添加了头部):
Accept: application/json
Content-type: application/json
当它不工作时的头部(cURL中没有头部):
Accept: */*
Content-Type: application/x-www-form-urlencoded
是否有任何方法可以强制设置头部,而不是要求用户提供它们?
英文:
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
得分: 1
Content-type
是一个重要的HTTP头部,它让服务器决定如何解析HTTP主体。
有没有办法强制设置头部而不是要求用户提供它们?
很难说是或否,这取决于你的“用户”。对于curl来说,它无法猜测HTTP主体的格式并自动将Content-Type设置为“application/json”,所以你需要指定Content-Type。对于其他像jQuery这样的库,程序员可以在post请求中设置dataType
,例如jQuery.post( url [, data ] [, success ] [, dataType ] )
链接。
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论