is there a easy way to unzip file with golang ?
right now my code is:
func Unzip(src, dest string) error {
r, err := zip.OpenReader(src)
if err !
Every single answer on this page is wrong, as they all assume that the Zip archive will emit directory entries. Zip archives are not required to emit directory entries, and so given an archive such as that, a naive program will crash upon encountering the first non-root file, as no directories will ever be created, and the file creation will fail as the directory has not been created yet. Here is a different approach:
package main
import (
"archive/zip"
"os"
"path"
)
func Unzip(source string) error {
zip_o, e := zip.OpenReader(source)
if e != nil {
return e
}
for _, file_o := range zip_o.File {
if file_o.Mode().IsDir() {
continue
}
dir_s := path.Dir(file_o.Name)
os.MkdirAll(dir_s, os.ModeDir)
open_o, e := file_o.Open()
if e != nil {
return e
}
create_o, e := os.Create(file_o.Name)
if e != nil {
return e
}
create_o.ReadFrom(open_o)
}
return nil
}
Example use:
package main
import "log"
func main() {
e := Unzip("Microsoft.VisualCpp.Tools.HostX64.TargetX64.vsix")
if e != nil {
log.Fatal(e)
}
}