Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Siddhant-K-code/467f797a1e222ecb9afeaf86785f0b71 to your computer and use it in GitHub Desktop.
Save Siddhant-K-code/467f797a1e222ecb9afeaf86785f0b71 to your computer and use it in GitHub Desktop.
How to gzip compress and decompress files using the compress/gzip package in Go.

Gzip and Decompress Files in Go

This Gist demonstrates how to gzip compress and decompress files using the compress/gzip package in Go.

Compress a File

This Go program compresses a file named hello.txt into a gzip file named hello.txt.gz using the best compression level available.

package main

import (
	"compress/gzip"
	"io"
	"os"
)

func main() {
	dist, err := os.Create("hello.txt.gz")
	if err != nil {
		panic(err)
	}
	defer dist.Close()

	// Use the best compression level
	gw, err := gzip.NewWriterLevel(dist, gzip.BestCompression)
	if err != nil {
		panic(err)
	}
	defer gw.Close()

	src, err := os.Open("hello.txt")
	if err != nil {
		panic(err)
	}
	defer src.Close()

	if _, err := io.Copy(gw, src); err != nil {
		panic(err)
	}
}

Decompress a File

This Go program decompresses a file named hello.txt.gz back to a file named hello.txt.

package main

import (
	"compress/gzip"
	"io"
	"os"
)

func main() {
	dist, err := os.Create("hello.txt")
	if err != nil {
		panic(err)
	}
	defer dist.Close()

	src, err := os.Open("hello.txt.gz")
	if err != nil {
		panic(err)
	}
	defer src.Close()

	gr, err := gzip.NewReader(src)
	if err != nil {
		panic(err)
	}
	defer gr.Close()

	if _, err := io.Copy(dist, gr); err != nil {
		panic(err)
	}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment