I'm trying to compress a string with Gzip and uncompress it, but it doesn't work as I expected.
My code is the following where I compress "hello World" and then read/decompress it
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)
I expect it to return "hello world" but it returns 0
..
If I remove l, _ := r.Read(s)
and replace the last line with log.Println(r)
I get this which doesn't quite makes sense
&{{ [] 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>}
Can someone explain me where I'm wrong?
What I want is just compress a string and return its decompressed result later.
Finish writing the output. For example,
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))
}
Output:
2009/11/10 23:00:00 11 hello world