普通网友 2019-04-10 00:02
浏览 1206
已采纳

用golang解压缩gzip字符串

I have a string which contains a gzip compressed string, therefore there's no file headers, standard compress/gzip library throws error gzip: invalid header

How can I decompress a gzip compressed string in go?

This is what I'm trying

nbody := "eNorTk0uSi0BAAjRAoc="
rdata := strings.NewReader(nbody)
r,err := gzip.NewReader(rdata)
log.Println(r)
if err != nil {
    log.Fatal(err)
}
s, _ := ioutil.ReadAll(r)
fmt.Println(string(s))
  • 写回答

2条回答 默认 最新

  • duanjinchen5296 2019-04-10 01:00
    关注

    ... I have a string which contains a gzip compressed string

    nbody := "eNorTk0uSi0BAAjRAoc="
    

    This is not a "gzip compressed string". This looks like some base64 encoded data which need to be decoded first. After decoding it is not gzip either but zlib - which is basically the same as gzip (content compressed with deflate algorithm) but with a different file header. Therefore trying to decode it with gzip will not work.

    The following will therefore take your original string, decode it from base64 and decompress it using zlib (not gzip):

    package main
    
    import (
            "bytes"
            "compress/zlib"
            "encoding/base64"
            "fmt"
            "io/ioutil"
    )
    
    func main() {
            b64z := "eNorTk0uSi0BAAjRAoc="
            z, _ := base64.StdEncoding.DecodeString(b64z)
            r, _ := zlib.NewReader(bytes.NewReader(z))
            result, _ := ioutil.ReadAll(r)
            fmt.Println(string(result))  // results in "secret"
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?