Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 442
pymd Avatar asked Jun 03 '13 05:06

pymd


People also ask

How do I compress components with gzip?

The easiest way to enable GZIP compression on your WordPress site is by using a caching or performance optimization plugin. For example, if you host your WordPress site on Apache web server, W3 Total Cache includes an option to enable GZIP compression under its Browser Cache settings panel.

How does gzip compress work?

GZIP compression is a data-compressing process through which the size of a file is reduced before it is transferred from the server to the browser. So, a GZIP compressed file is smaller in size when compared to the original, thus the browser renders its contents faster.

How do I gzip a file in Golang?

Copy all read bytes into the new file and close the file By using gzip. NewWriter() from the compress/gzip package, we create a new gzip writer. Then we can use Write to write the compressed bytes in the file. After finishing, we need to close the file.


2 Answers

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()
like image 194
laurent Avatar answered Oct 06 '22 11:10

laurent


Pretty much the same answer as Laurent, but with the file io:

import (
  "bytes"
  "compress/gzip"
  "io/ioutil"
)
// ...
var b bytes.Buffer
w := gzip.NewWriter(&b)
w.Write([]byte("hello, world\n"))
w.Close() // You must close this first to flush the bytes to the buffer.
err := ioutil.WriteFile("hello_world.txt.gz", b.Bytes(), 0666)
like image 11
Kevin Cantwell Avatar answered Oct 06 '22 10:10

Kevin Cantwell