This Gist demonstrates how to gzip compress and decompress files using the compress/gzip
package in Go.
This Go program compresses a file named hello.txt
into a gzip file named hello.txt.gz
using the best compression level available.
package main
import (
"compress/gzip"
"io"
"os"
)
func main() {
dist, err := os.Create("hello.txt.gz")
if err != nil {
panic(err)
}
defer dist.Close()
// Use the best compression level
gw, err := gzip.NewWriterLevel(dist, gzip.BestCompression)
if err != nil {
panic(err)
}
defer gw.Close()
src, err := os.Open("hello.txt")
if err != nil {
panic(err)
}
defer src.Close()
if _, err := io.Copy(gw, src); err != nil {
panic(err)
}
}
This Go program decompresses a file named hello.txt.gz
back to a file named hello.txt
.
package main
import (
"compress/gzip"
"io"
"os"
)
func main() {
dist, err := os.Create("hello.txt")
if err != nil {
panic(err)
}
defer dist.Close()
src, err := os.Open("hello.txt.gz")
if err != nil {
panic(err)
}
defer src.Close()
gr, err := gzip.NewReader(src)
if err != nil {
panic(err)
}
defer gr.Close()
if _, err := io.Copy(dist, gr); err != nil {
panic(err)
}
}