To create a compressed gzip file from data in Go, you can use the compress/gzip
package.
Here is an example:
package main
import (
"compress/gzip"
"fmt"
"log"
"os"
)
func main() {
// Open the output gzip file
outputFile, err := os.Create("output.gz")
if err != nil {
log.Fatal(err)
}
defer outputFile.Close()
// Create a gzip writer
gzipWriter := gzip.NewWriter(outputFile)
defer gzipWriter.Close()
// Write data to the gzip writer
data := []byte("This is the content of the gzip file.")
_, err = gzipWriter.Write(data)
if err != nil {
log.Fatal(err)
}
// Flush the gzip writer to ensure all data is written
err = gzipWriter.Flush()
if err != nil {
log.Fatal(err)
}
fmt.Println("Gzip file created successfully.")
}
In the above example, we create a new gzip file named "output.gz" using os.Create
. Then we create a gzip.Writer
to write compressed data to the file. After writing the data, we need to flush the writer using Flush
to ensure all data is written to the file.
Note that we defer closing both the gzip writer and the output file. Defer ensures that the resources are properly closed when the program finishes executing.
By running the above code, you will create a compressed gzip file named "output.gz" containing the provided data.