How to compress and decompress data using the compress/lzw package in Go?

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

  1. Import the compress/lzw package.
import "compress/lzw"
  1. To compress the data, create a new io.Writer using lzw.NewWriter function. Pass the destination writer and the compression level to the function. The compression level should be between 0 and 9, where 0 means no compression and 9 means maximum compression.
compressedData := make([]byte, 0) compressWriter := lzw.NewWriter(&compressedData, lzw.MSB, 8)
  1. Write the data to be compressed using the Write method of the compress.Writer.
compressWriter.Write([]byte("Data to be compressed"))
  1. After writing the data, close the compress.Writer to flush any remaining compressed data and update the compressed data slice.
compressWriter.Close()
  1. To decompress the data, create a new io.Reader using the lzw.NewReader function. Pass the source reader, such as bytes from a compressed file, and lzw.MSB, which represents the most significant bit first.
decompressReader := lzw.NewReader(bytes.NewReader(compressedData), lzw.MSB, 8)
  1. Use the Read method of the decompress.Reader to read the decompressed data.
decompressedData := make([]byte, 0) decompressReader.Read(decompressedData)
  1. Close the compress.Reader to release any associated resources.
decompressReader.Close()

That's it! You have now compressed and decompressed data using the compress/lzw package in Go.