Golang : Gunzip file
This tutorial demonstrates how to g-unzip a gz
file easily in Golang. It is a continuation from previous tutorial on how to unzip a zip archive.
gunzip.go
package main
import (
"compress/gzip"
"flag"
"fmt"
"io"
"os"
"strings"
)
func main() {
flag.Parse() // get the arguments from command line
filename := flag.Arg(0)
if filename == "" {
fmt.Println("Usage : gunzip sourcefile.gz")
os.Exit(1)
}
gzipfile, err := os.Open(filename)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
reader, err := gzip.NewReader(gzipfile)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
defer reader.Close()
newfilename := strings.TrimSuffix(filename, ".gz")
writer, err := os.Create(newfilename)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
defer writer.Close()
if _, err = io.Copy(writer, reader); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
Outputs (example) :
./gunzip
Usage : gunzip sourcefile.gz
This program will not produce any message upon successful decompression of gzipped file.
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+22.2k Golang : How to run Golang application such as web server in the background or as daemon?
+7.7k Golang : Command line ticker to show work in progress
+7.1k Golang : Validate credit card example
+6.2k Golang : Get missing location after unmarshal binary and gob decode time.
+24.1k Golang : Upload to S3 with official aws-sdk-go package
+21.3k Golang : Create and resolve(read) symbolic links
+26.4k Golang : Convert(cast) string to uint8 type and back to string
+13.1k Golang : Convert(cast) uintptr to string example
+12.5k Elastic Search : Return all records (higher than default 10)
+11.3k Golang : How to use if, eq and print properly in html template
+12.2k Golang : Detect user location with HTML5 geo-location