To compress data using the compress/zlib package in Go, you can follow these steps:
import (
"bytes"
"compress/zlib"
"fmt"
"io/ioutil"
)
func compressData(data []byte) ([]byte, error) {
var buf bytes.Buffer
w := zlib.NewWriter(&buf)
_, err := w.Write(data)
if err != nil {
return nil, err
}
err = w.Close()
if err != nil {
return nil, err
}
return buf.Bytes(), nil
}
func main() {
// Sample data to compress
data := []byte("Lorem ipsum dolor sit amet")
compressedData, err := compressData(data)
if err != nil {
fmt.Println("Compression failed:", err)
return
}
fmt.Println("Original data size:", len(data))
fmt.Println("Compressed data size:", len(compressedData))
}
The compressData function takes a byte slice as input and returns a compressed byte slice. It uses a zlib.Writer
to compress the data and writes it to a buffer. Finally, it closes the writer and returns the compressed data.
Note: Make sure to handle any errors that may occur during compression or decompression.