zip.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. package utils
  2. import (
  3. "archive/zip"
  4. "io"
  5. "os"
  6. "path"
  7. "path/filepath"
  8. )
  9. // Unzip decompresses a zip file to specified directory.
  10. // Note that the destination directory don't need to specify the trailing path separator.
  11. func Unzip(zipPath, dstDir string) error {
  12. // open zip file
  13. reader, err := zip.OpenReader(zipPath)
  14. if err != nil {
  15. return err
  16. }
  17. defer reader.Close()
  18. for _, file := range reader.File {
  19. if err := unzipFile(file, dstDir); err != nil {
  20. return err
  21. }
  22. }
  23. return nil
  24. }
  25. func unzipFile(file *zip.File, dstDir string) error {
  26. // create the directory of file
  27. filePath := path.Join(dstDir, file.Name)
  28. if file.FileInfo().IsDir() {
  29. if err := os.MkdirAll(filePath, os.ModePerm); err != nil {
  30. return err
  31. }
  32. return nil
  33. }
  34. if err := os.MkdirAll(filepath.Dir(filePath), os.ModePerm); err != nil {
  35. return err
  36. }
  37. // open the file
  38. rc, err := file.Open()
  39. if err != nil {
  40. return err
  41. }
  42. defer rc.Close()
  43. // create the file
  44. w, err := os.Create(filePath)
  45. if err != nil {
  46. return err
  47. }
  48. defer w.Close()
  49. // save the decompressed file content
  50. _, err = io.Copy(w, rc)
  51. return err
  52. }