我正在开发一个web应用程序,在这个应用程序中,我使用golang gin-gonic框架来创建rest API,我想从gzip格式的上下文体中读取数据,为了gzip压缩JSON数据,我使用angular框架pako包,这个包工作得很好,可以将JSON数据转换为gzip压缩的数据。现在在我的golang应用程序中,我想gunzip压缩的数据,我用下面的话来解释
我用的是gzip包。
在我的路由器文件中,我添加了
router := gin.Default()
router.Use(gzip.Gzip(gzip.DefaultCompression))
字符串
我做了一个测试功能,但有错误,而阅读数据
func Test(c *gin.Context) {
if c.GetHeader("Content-Encoding") == "gzip" {
// Read the gzipped data from the request body
gzippedBody, err := ioutil.ReadAll(c.Request.Body)
if err != nil {
c.String(http.StatusBadRequest, "Failed to read request body")
return
}
defer c.Request.Body.Close()
buf := bytes.NewReader(gzippedBody)
// Create a new reader for the gzip data
reader, err := gzip.NewReader(buf)
if err != nil {
c.String(http.StatusInternalServerError, "Failed to create gzip reader")
return
}
defer reader.Close()
// Read the decompressed data
uncompressedBody, err := ioutil.ReadAll(reader)
if err != nil {
c.String(http.StatusInternalServerError, "Failed to read decompressed body")
return
}
// Now uncompressedBody contains the decompressed data
fmt.Println("Decompressed data:", string(uncompressedBody))
// Handle the uncompressed data as needed
// ...
// Send a response
c.String(http.StatusOK, "Received and decompressed data successfully")
} else {
c.String(http.StatusBadRequest, "Expected gzipped data in request")
}
return
}
型
错误是-> gzip:无效的头
有谁能解释一下,让我知道为了得到想要的结果需要纠正什么吗
1条答案
按热度按时间sshcrbum1#
gin gzip中间件已经可以为您处理这个问题。下面是相关的测试用例:
https://github.com/gin-contrib/gzip/blob/master/gzip_test.go#L196C1-L219
基本上,只要改变
字符串
到
型