How to create and read compressed data from an HTTP response in Go?

To create and read compressed data from an HTTP response in Go, you can make use of the gzip package in the standard library. Here's an example that demonstrates creating and reading compressed data from an HTTP response:

package main import ( "compress/gzip" "io" "net/http" "os" ) func main() { url := "https://example.com" // replace with your desired URL response, err := http.Get(url) if err != nil { panic(err) } defer response.Body.Close() var reader io.ReadCloser switch response.Header.Get("Content-Encoding") { case "gzip": reader, err = gzip.NewReader(response.Body) if err != nil { panic(err) } defer reader.Close() default: reader = response.Body } // Create a file to save the decompressed data file, err := os.Create("output.txt") if err != nil { panic(err) } defer file.Close() // Copy the decompressed data to the file _, err = io.Copy(file, reader) if err != nil { panic(err) } }

In this example, we first send an HTTP GET request to the desired URL using http.Get(). The HTTP response is then checked for the Content-Encoding header, which indicates if the response is compressed. If the content is compressed using gzip, we create a new gzip.Reader to decompress the response body, and if not, we directly use the response body.

Then, we create a file to save the decompressed data and copy the decompressed data from the response body (or gzip reader) to the file using io.Copy().

Remember to replace the url variable with the actual URL you want to retrieve and decompress.