Skip to content

Instantly share code, notes, and snippets.

@purpleidea
Created September 4, 2024 01:10
Show Gist options
  • Save purpleidea/a4155baafa1da3cb431b1c05798785bc to your computer and use it in GitHub Desktop.
Save purpleidea/a4155baafa1da3cb431b1c05798785bc to your computer and use it in GitHub Desktop.
Simple golang gzip compression
// Thanks purpleidea for putting this together!
// Why isn't this the default example in the golang docs?
package main
import (
"compress/gzip"
"fmt"
"io"
"os"
)
func main() {
dest := "/tmp/output.gz"
input := "/tmp/input.tar"
inputFile, err := os.Open(input) // io.Reader
if err != nil {
panic(err)
}
defer inputFile.Close()
outputFile, err := os.Create(dest) // io.Writer
if err != nil {
panic(err)
}
defer outputFile.Close()
level := gzip.BestSpeed
gzipWriter, err := gzip.NewWriterLevel(outputFile, level) // (*gzip.Writer, error)
if err != nil {
panic(err)
}
defer gzipWriter.Close()
// Copy the input file into the writer, which writes it out compressed.
bytes, err := io.Copy(gzipWriter, inputFile) // dst, src
if err != nil {
panic(err)
}
fmt.Printf("wrote: %+v\n", bytes)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment