How to decompress a gzip file in Go?

To decompress a gzip file in Go, you can use the compress/gzip package. Here's a step-by-step guide on how to achieve this:

  1. Import the necessary packages:
import ( "compress/gzip" "fmt" "io" "os" )
  1. Open the gzip file for reading:
file, err := os.Open("compressed_file.gzip") if err != nil { fmt.Println("Error opening file:", err) return } defer file.Close()
  1. Create a gzip reader:
gzipReader, err := gzip.NewReader(file) if err != nil { fmt.Println("Error creating gzip reader:", err) return } defer gzipReader.Close()
  1. Create a file to write the decompressed data:
outputFile, err := os.Create("decompressed_file.txt") if err != nil { fmt.Println("Error creating output file:", err) return } defer outputFile.Close()
  1. Copy the decompressed data from the gzip reader to the output file:
_, err = io.Copy(outputFile, gzipReader) if err != nil { fmt.Println("Error decompressing file:", err) return }
  1. Print a success message:
fmt.Println("File decompressed successfully.")

That's it! The above code will decompress the gzip file and save the decompressed data to the specified output file. Make sure to replace "compressed_file.gzip" with the actual path of your gzip file, and "decompressed_file.txt" with the desired output file path.