How to compress and decompress data using encoding formats (e.g., gzip) in Go?

To compress and decompress data using encoding formats like gzip in Go, you can make use of the compress/gzip package in the Go standard library.

Here's an example that demonstrates how to compress and decompress data using gzip in Go:

package main import ( "bytes" "compress/gzip" "fmt" "io/ioutil" ) func main() { // Original data data := []byte("Lorem ipsum dolor sit amet, consectetur adipiscing elit.") // Compressing data var compressedData bytes.Buffer gzipWriter := gzip.NewWriter(&compressedData) _, err := gzipWriter.Write(data) if err != nil { panic(err) } gzipWriter.Close() fmt.Printf("Compressed data: %v\n", compressedData.Bytes()) // Decompressing data gzipReader, err := gzip.NewReader(bytes.NewReader(compressedData.Bytes())) if err != nil { panic(err) } decompressedData, err := ioutil.ReadAll(gzipReader) if err != nil { panic(err) } gzipReader.Close() fmt.Printf("Decompressed data: %s\n", string(decompressedData)) }

In the above code, we define the original data we want to compress. We then create a bytes.Buffer to store the compressed data. We create a gzip.Writer using the buffer and write the original data to it. Finally, we close the gzip.Writer to flush any remaining data and complete the compression.

To decompress the data, we create a gzip.Reader using the bytes.Buffer containing the compressed data. We then read all the decompressed data from the gzip.Reader and close it.

After running this code, you should see the compressed and decompressed data printed to the console.