Created
September 4, 2024 01:10
-
-
Save purpleidea/a4155baafa1da3cb431b1c05798785bc to your computer and use it in GitHub Desktop.
Simple golang gzip compression
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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