Search code examples
file-iocompressiongogzip

How can I use the "compress/gzip" package to gzip a file?


I'm new to Go, and can't figure out how to use the compress/gzip package to my advantage. Basically, I just want to write something to a file, gzip it and read it directly from the zipped format through another script. I would really appreciate if someone could give me an example on how to do this.


Solution

  • All the compress packages implement the same interface. You would use something like this to compress:

    var b bytes.Buffer
    w := gzip.NewWriter(&b)
    w.Write([]byte("hello, world\n"))
    w.Close()
    

    And this to unpack:

    r, err := gzip.NewReader(&b)
    io.Copy(os.Stdout, r)
    r.Close()