Last active
April 14, 2016 06:17
-
-
Save ken5scal/d2d3b4bc6b5fe749b68c9f083baa29de to your computer and use it in GitHub Desktop.
ZIP by GO (Copied from [StackOverFlow](http://stackoverflow.com/questions/20357223/easy-way-to-unzip-file-with-golang))
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"archive/zip" | |
"fmt" | |
"io" | |
"log" | |
"os" | |
"path/filepath" | |
) | |
func main() { | |
fmt.Println("Hogehoge") | |
err := Unzip("./HOGE.zip", ".") | |
if err != nil { | |
log.Fatal(err) | |
} | |
} | |
func Unzip(src, dest string) error { | |
r, err := zip.OpenReader(src) | |
if err != nil { | |
return err | |
} | |
defer func() { | |
if err := r.Close(); err != nil { | |
panic(err) | |
} | |
}() | |
os.MkdirAll(dest, 0755) | |
// Closure to address file descritpors issue with all the defered.close method | |
extractAndWriteFile := func(f *zip.File) error { | |
rc, err := f.Open() | |
if err != nil { | |
return err | |
} | |
defer func() { | |
if err := rc.Close(); err != nil { | |
panic(err) | |
} | |
}() | |
path := filepath.Join(dest, f.Name) | |
if f.FileInfo().IsDir() { | |
os.MkdirAll(path, f.Mode()) | |
} else { | |
f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, f.Mode()) | |
if err != nil { | |
return err | |
} | |
defer func() { | |
if err := f.Close(); err != nil { | |
panic(err) | |
} | |
}() | |
_, err = io.Copy(f, rc) | |
if err != nil { | |
return err | |
} | |
} | |
return nil | |
} | |
for _, f := range r.File { | |
err := extractAndWriteFile(f) | |
if err != nil { | |
return err | |
} | |
} | |
return nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Copied from this StackOverFlow for Go Practice as well as future reference