To use the compress/flate
package in Go to compress and decompress streams of data, you would typically follow these steps:
import (
"compress/flate"
"io"
"os"
)
Writer
object with the desired compression level and output destination:outputFile, err := os.Create("compressed.dat")
if err != nil {
panic(err)
}
defer outputFile.Close()
compressor, err := flate.NewWriter(outputFile, flate.BestCompression)
if err != nil {
panic(err)
}
defer compressor.Close()
compressor
:data := []byte("Data to be compressed")
_, err = compressor.Write(data)
if err != nil {
panic(err)
}
compressor
to ensure all data is written and compressed correctly:err = compressor.Close()
if err != nil {
panic(err)
}
Now you have a compressed stream of data in the compressed.dat
file.
Reader
from your compressed stream file:compressedFile, err := os.Open("compressed.dat")
if err != nil {
panic(err)
}
defer compressedFile.Close()
decompressor := flate.NewReader(compressedFile)
defer decompressor.Close()
byte
slice to read the decompressed data into:decompressedData := make([]byte, 1024)
n, err := decompressor.Read(decompressedData)
if err != nil && err != io.EOF {
panic(err)
}
n
variable to determine the actual number of bytes read, which is the decompressed data length. You can use only decompressedData[:n]
to access the decompressed data:fmt.Println(string(decompressedData[:n]))
That's it! You've successfully compressed and decompressed streams of data using the compress/flate
package in Go.