我试图用Gzip压缩字符串并解压缩它,但它并没有像我预期的那样工作。
我的代码是以下我压缩"你好世界"然后读取/解压缩
s := []byte("hello world")
var b bytes.Buffer
gz := gzip.NewWriter(&b)
defer gz.Close()
_, err = gz.Write(s)
if err != nil {
panic(err)
}
r, err := gzip.NewReader(&b)
defer r.Close()
if err != nil {
panic(err)
}
l, _ := r.Read(s)
log.Println(l)
我希望它能回归"你好世界"但它返回0
..
如果我删除l, _ := r.Read(s)
并将最后一行替换为log.Println(r)
,我会得到这个没有意义的
&{{ [] 2042-07-14 02:04:00 +0100 CET 255} 0x1847b780 0x185aa000 0x18400db8 0 0 [31 139 8 0 0 9 110 136 0 255 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] <nil>}
有人可以解释一下我错在哪里吗?
我想要的只是压缩一个字符串并稍后返回它的解压缩结果。
答案 0 :(得分:1)
完成输出的写入。例如,
package main
import (
"bytes"
"compress/gzip"
"log"
)
func main() {
var b bytes.Buffer
w := gzip.NewWriter(&b)
s := []byte("hello world")
_, err := w.Write(s)
if err != nil {
panic(err)
}
err = w.Flush()
if err != nil {
panic(err)
}
err = w.Close()
if err != nil {
panic(err)
}
r, err := gzip.NewReader(&b)
if err != nil {
panic(err)
}
defer r.Close()
t := make([]byte, len(s))
l, err := r.Read(t)
if err != nil {
panic(err)
}
log.Println(l, string(t))
}
输出:
2009/11/10 23:00:00 11 hello world