How to compress data using the compress/zlib package in Go?

To compress data using the compress/zlib package in Go, you can follow these steps:

  1. Import the required packages:
import ( "bytes" "compress/zlib" "fmt" "io/ioutil" )
  1. Create a function to compress the data:
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 }
  1. Use the compressData function to compress your data:
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.