To read and write data to compressed files in Go, you can use the gzip
package from the standard library. Here's an example of how to use it:
import (
"compress/gzip"
"os"
)
// Open the compressed file for reading
file, err := os.Open("compressedFile.gz")
if err != nil {
panic(err)
}
defer file.Close()
// Create a gzip reader
gzipReader, err := gzip.NewReader(file)
if err != nil {
panic(err)
}
defer gzipReader.Close()
// Read the uncompressed data from the gzip reader
buffer := make([]byte, 4096)
for {
bytesRead, err := gzipReader.Read(buffer)
if err != nil {
panic(err)
}
// Process the uncompressed data
if bytesRead == 0 {
break
}
}
// Create the output file for writing
outputFile, err := os.Create("outputFile.gz")
if err != nil {
panic(err)
}
defer outputFile.Close()
// Create a gzip writer
gzipWriter := gzip.NewWriter(outputFile)
defer gzipWriter.Close()
// Write the compressed data to the gzip writer
data := []byte("Some data to compress")
_, err = gzipWriter.Write(data)
if err != nil {
panic(err)
}
// Flush any remaining compressed data to the output file
err = gzipWriter.Flush()
if err != nil {
panic(err)
}
Make sure to handle any errors appropriately according to your use case.