我有一个包含gzip压缩字符串的字符串,因此没有文件头,标准compress/gzip库抛出错误gzip: invalid header
如何在go中解压缩gzip压缩字符串?
这就是我正在尝试的
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))
Run Code Online (Sandbox Code Playgroud)
Bra*_*lta 20
由于这个问题一直在 google 上出现,如果您在字符串中有真正的 gzip 编码数据并且想要对其进行解码,那么您将如何做到这一点:
import "compress/gzip";
import "bytes";
import "io/ioutil";
...
original := "gzipencodeddata";
reader := bytes.NewReader([]byte(original))
gzreader, e1 := gzip.NewReader(reader);
if(e1 != nil){
fmt.Println(e1); // Maybe panic here, depends on your error handling.
}
output, e2 := ioutil.ReadAll(gzreader);
if(e2 != nil){
fmt.Println(e2);
}
result := string(output);
Run Code Online (Sandbox Code Playgroud)
...我有一个包含gzip压缩字符串的字符串
Run Code Online (Sandbox Code Playgroud)nbody := "eNorTk0uSi0BAAjRAoc="
这不是“ gzip压缩字符串”。看起来有些需要先解码的base64编码数据。解码后,它也不是gzip,而是zlib-与gzip(使用deflate算法压缩的内容)基本相同,但是文件头不同。因此,尝试使用gzip对其进行解码将不起作用。
因此,以下代码将使用您的原始字符串,从base64对其进行解码,然后使用zlib(而非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"
}
Run Code Online (Sandbox Code Playgroud)