zip.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. // Copyright 2021 EMQ Technologies Co., Ltd.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package filex
  15. import (
  16. "archive/zip"
  17. "fmt"
  18. "io"
  19. "os"
  20. "path/filepath"
  21. )
  22. func UnzipTo(f *zip.File, fpath string) error {
  23. _, err := os.Stat(fpath)
  24. if f.FileInfo().IsDir() {
  25. // Make Folder
  26. if _, err := os.Stat(fpath); os.IsNotExist(err) {
  27. if err := os.MkdirAll(fpath, os.ModePerm); err != nil {
  28. return err
  29. }
  30. }
  31. return nil
  32. }
  33. if err == nil || !os.IsNotExist(err) {
  34. if err = os.RemoveAll(fpath); err != nil {
  35. return fmt.Errorf("failed to delete file %s", fpath)
  36. }
  37. }
  38. if _, err := os.Stat(filepath.Dir(fpath)); os.IsNotExist(err) {
  39. if err := os.MkdirAll(filepath.Dir(fpath), os.ModePerm); err != nil {
  40. return err
  41. }
  42. }
  43. outFile, err := os.OpenFile(fpath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, f.Mode())
  44. if err != nil {
  45. return err
  46. }
  47. rc, err := f.Open()
  48. if err != nil {
  49. return err
  50. }
  51. _, err = io.Copy(outFile, rc)
  52. outFile.Close()
  53. rc.Close()
  54. return err
  55. }