Gunzip the gzip data from context request body in golang

167 Views Asked by At

I am working on a web app, in which i'm using golang gin-gonic framework for creating rest api's, i want to read data from context body which is in gzip format, for gzipping the json data i'm using angular framework pako package,This package works pretty well and makes json data to gzip-compressed data. Now in my golang app i want to gunzip the gzipped data, for which i'm using the following-

i'm using gzip package.

in my router file i have added

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

I have made an Test function for this but there is error while reading the data

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
}

error is -> gzip: invalid header

Can anyone explain and let me know what needs to be corrected in order to get the desired result

1

There are 1 best solutions below

0
On

The gin gzip middleware can already handle this for you. Here is the relevant test case:

https://github.com/gin-contrib/gzip/blob/master/gzip_test.go#L196C1-L219

Basically, just change

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

to

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