Golang : Unzip file
Go's standard library provides support for several archive file formats. Zip format is the most common standard of compressing file. It is easy to unzip zip file in Go. Below is the code to unzip a zip file.
gounzip.go
package main
import (
"archive/zip"
"flag"
"fmt"
"io"
"os"
"path/filepath"
)
func main() {
flag.Parse() // get the arguments from command line
zipfile := flag.Arg(0)
if zipfile == "" {
fmt.Println("Usage : gounzip sourcefile.zip")
os.Exit(1)
}
reader, err := zip.OpenReader(zipfile)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
defer reader.Close()
for _, f := range reader.Reader.File {
zipped, err := f.Open()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
defer zipped.Close()
// get the individual file name and extract the current directory
path := filepath.Join("./", f.Name)
if f.FileInfo().IsDir() {
os.MkdirAll(path, f.Mode())
fmt.Println("Creating directory", path)
} else {
writer, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE, f.Mode())
if err != nil {
fmt.Println(err)
os.Exit(1)
}
defer writer.Close()
if _, err = io.Copy(writer, zipped); err != nil {
fmt.Println(err)
os.Exit(1)
}
fmt.Println("Decompressing : ", path)
}
}
}
Build the executable and
test out the
./gounzip somefile.zip
Sample out :
./gounzip v1.8.31.2-beta.zip
Creating directory ngx_pagespeed-1.8.31.2-beta
Decompressing : ngx_pagespeed-1.8.31.2-beta/.gitignore
Decompressing : ngx_pagespeed-1.8.31.2-beta/LICENSE
Decompressing : ngx_pagespeed-1.8.31.2-beta/README.md
Decompressing : ngx_pagespeed-1.8.31.2-beta/config
Decompressing : ngxpagespeed-1.8.31.2-beta/cppfeature
Creating directory ngx_pagespeed-1.8.31.2-beta/scripts
...
References:
See also : Golang : Zip 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
+13.1k Golang : Generate Code128 barcode
+3.5k Golang : Switch Redis database redis.NewClient
+10.3k RPM : error: db3 error(-30974) from dbenv->failchk: DB_RUNRECOVERY: Fatal error, run database recovery
+6.8k Golang : How to call function inside template with template.FuncMap
+12.1k Golang : flag provided but not defined error
+14.2k Golang : Send email with attachment(RFC2822) using Gmail API example
+11.1k Golang : Fix fmt.Scanf() on Windows will scan input twice problem
+7.3k Golang : Rename part of filename
+7.6k Golang : Example of how to detect which type of script a word belongs to
+4.3k Java : Generate multiplication table example
+34.3k Golang : How to stream file to client(browser) or write to http.ResponseWriter?
+8.8k Golang : How to capture return values from goroutines?