我想编写一个 api,它将通过 POST 发送 gzip 压缩的 json 数据。虽然下面可以处理正文中的简单 json,但如果 json 被压缩,则不处理。
使用前是否需要明确处理解压c.ShouldBindJSON?
如何重现
package main
import (
"github.com/gin-gonic/gin"
"log"
"net/http"
)
func main() {
r := gin.Default()
r.POST("/postgzip", func(c *gin.Context) {
type PostData struct {
Data string `binding:"required" json:"data"`
}
var postdata PostData
if err := c.ShouldBindJSON(&postdata); err != nil {
log.Println("Error parsing request body", "error", err)
c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
log.Printf("%s", postdata)
if !c.IsAborted() {
c.String(200, postdata.Data)
}
})
r.Run()
}
❯ echo '{"data" : "hello"}' | curl -X POST -H "Content-Type: application/json" -d @- localhost:8080/postgzip
hello
期望
$ echo '{"data" : "hello"}' | gzip | curl -v -i -X POST -H "Content-Type: application/json" -H "Content-Encoding: gzip" --data-binary @- localhost:8080/postgzip
hello
实际结果
$ echo '{"data" : "hello"}' | gzip | curl -v -i -X POST -H "Content-Type: application/json" -H "Content-Encoding: gzip" --data-binary @- localhost:8080/postgzip
{"error":"invalid character '\\x1f' looking for beginning of value"}
去版本:go version go1.17.2 darwin/amd64
gin 版本(或提交参考):v1.7.4
操作系统:MacOS Monterey
慕容森
阿波罗的战车
相关分类