为什么这不起作用? (对不起因为某些原因我无法在Go Playground上获得分享按钮)。
package main
import (
"bytes"
"compress/gzip"
"fmt"
"io"
)
func main() {
// ENCODE
data := []byte{1, 2, 3, 4, 5, 6, 7}
bb0 := bytes.NewBuffer(data)
byts := bb0.Bytes()
fmt.Printf("data = % x\n", data)
fmt.Printf("byte buffer bb0 contains = % x\n", byts)
bb1 := new(bytes.Buffer)
w := gzip.NewWriter(bb1)
s1, err := w.Write(byts)
fmt.Printf("%d bytes written using gzip writer, err = %v\n", s1, err)
byts = bb1.Bytes()
fmt.Printf("byte buffer bb1 contains = % x\n", byts)
// DECODE
r, err := gzip.NewReader(bb1)
bb2 := new(bytes.Buffer)
s2, err := io.Copy(bb2, r)
r.Close()
fmt.Printf("%d bytes copied from gzip reader, err = %v\n", s2, err)
byts = bb2.Bytes()
fmt.Printf("byte buffer bb2 contains = % x\n", byts)
}
我得到的输出
data = 01 02 03 04 05 06 07
byte buffer bb0 contains = 01 02 03 04 05 06 07
7 bytes written using gzip writer, err = <nil>
byte buffer bb1 contains = 1f 8b 08 00 00 09 6e 88 00 ff
0 bytes copied from gzip reader, err = unexpected EOF
byte buffer bb2 contains =
读者似乎没有做任何事情,我做错了什么?
答案 0 :(得分:6)
可能它不起作用,因为你没有关闭gzip编写器,因此gzip压缩数据从未刷新到底层编写器(你使用的是bytes.Buffer),或者至少它没有最终确定
写完后你需要w.Close()
gzip写手。
或者,可能是bytes.Buffer在尝试读取之前需要被寻找为零,因为它可能是读者试图从它的末尾读取。
你正在做的事情效率低下,我建议你使用:https://github.com/AlasdairF/Custom