Gunzip gzip从golang中的上下文请求体中的gzip数据

wz1wpwve  于 2024-01-04  发布在  Go
关注(0)|答案(1)|浏览(133)

我正在开发一个web应用程序,在这个应用程序中,我使用golang gin-gonic框架来创建rest API,我想从gzip格式的上下文体中读取数据,为了gzip压缩JSON数据,我使用angular框架pako包,这个包工作得很好,可以将JSON数据转换为gzip压缩的数据。现在在我的golang应用程序中,我想gunzip压缩的数据,我用下面的话来解释
我用的是gzip包。
在我的路由器文件中,我添加了

  1. router := gin.Default()
  2. router.Use(gzip.Gzip(gzip.DefaultCompression))

字符串
我做了一个测试功能,但有错误,而阅读数据

  1. func Test(c *gin.Context) {
  2. if c.GetHeader("Content-Encoding") == "gzip" {
  3. // Read the gzipped data from the request body
  4. gzippedBody, err := ioutil.ReadAll(c.Request.Body)
  5. if err != nil {
  6. c.String(http.StatusBadRequest, "Failed to read request body")
  7. return
  8. }
  9. defer c.Request.Body.Close()
  10. buf := bytes.NewReader(gzippedBody)
  11. // Create a new reader for the gzip data
  12. reader, err := gzip.NewReader(buf)
  13. if err != nil {
  14. c.String(http.StatusInternalServerError, "Failed to create gzip reader")
  15. return
  16. }
  17. defer reader.Close()
  18. // Read the decompressed data
  19. uncompressedBody, err := ioutil.ReadAll(reader)
  20. if err != nil {
  21. c.String(http.StatusInternalServerError, "Failed to read decompressed body")
  22. return
  23. }
  24. // Now uncompressedBody contains the decompressed data
  25. fmt.Println("Decompressed data:", string(uncompressedBody))
  26. // Handle the uncompressed data as needed
  27. // ...
  28. // Send a response
  29. c.String(http.StatusOK, "Received and decompressed data successfully")
  30. } else {
  31. c.String(http.StatusBadRequest, "Expected gzipped data in request")
  32. }
  33. return
  34. }


错误是-> gzip:无效的头
有谁能解释一下,让我知道为了得到想要的结果需要纠正什么吗

sshcrbum

sshcrbum1#

gin gzip中间件已经可以为您处理这个问题。下面是相关的测试用例:
https://github.com/gin-contrib/gzip/blob/master/gzip_test.go#L196C1-L219
基本上,只要改变

  1. router.Use(gzip.Gzip(gzip.DefaultCompression))

字符串

  1. router.Use(gzip.Gzip(gzip.DefaultCompression, gzip.WithDecompressFn(gzip.DefaultDecompressHandle)))

相关问题