easy way to unzip file with golang

后端 未结 8 773
情话喂你
情话喂你 2021-02-01 03:45

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 !         


        
8条回答
  •  爱一瞬间的悲伤
    2021-02-01 04:09

    I would prefer using 7zip with Go, which would give you something like this.

    func extractZip() {
        fmt.Println("extracting", zip_path)
        commandString := fmt.Sprintf(`7za e %s %s`, zip_path, dest_path)
        commandSlice := strings.Fields(commandString)
        fmt.Println(commandString)
        c := exec.Command(commandSlice[0], commandSlice[1:]...)
        e := c.Run()
        checkError(e)
    }
    

    Better example code

    However, if using 7zip isn't possible, then try this. Defer a recover to catch the panics. (Example)

    func checkError(e error){
      if e != nil {
        panic(e)
      }
    }
    func cloneZipItem(f *zip.File, dest string){
        // Create full directory path
        path := filepath.Join(dest, f.Name)
        fmt.Println("Creating", path)
        err := os.MkdirAll(filepath.Dir(path), os.ModeDir|os.ModePerm)
        checkError(err)
    
        // Clone if item is a file
        rc, err := f.Open()
        checkError(err)
        if !f.FileInfo().IsDir() {
            // Use os.Create() since Zip don't store file permissions.
            fileCopy, err := os.Create(path)
            checkError(err)
            _, err = io.Copy(fileCopy, rc)
            fileCopy.Close()
            checkError(err)
        }
        rc.Close()
    }
    func Extract(zip_path, dest string) {
        r, err := zip.OpenReader(zip_path)
        checkError(err)
        defer r.Close()
        for _, f := range r.File {
            cloneZipItem(f, dest)
        }
    }
    

提交回复
热议问题