easy way to unzip file with golang

后端 未结 8 775
情话喂你
情话喂你 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条回答
  •  猫巷女王i
    2021-02-01 04:22

    package main
    
    import (
        "os"
        "io"
        "io/ioutil"
        "fmt"
        "strings"
        "archive/zip"
        "path/filepath"
    )
    
    func main() {
        if err := foo("test.zip"); err != nil {
            fmt.Println(err)
        }
    }
    
    func foo(yourZipFile string) error {
        tmpDir, err := ioutil.TempDir("/tmp", "yourPrefix-")
        if err != nil {
            return err
        }
        defer os.RemoveAll(tmpDir)
        if filenames, err := Unzip(yourZipFile, tmpDir); err != nil {
            return err
        } else {
            for f := range filenames {
                fmt.Println(filenames[f])
            }
        }
        return nil
    }
    
    
    func Unzip(src string, dst string) ([]string, error) {
        var filenames []string
        r, err := zip.OpenReader(src)
        if err != nil {
            return nil, err
        }
        defer r.Close()
        for f := range r.File {
            dstpath := filepath.Join(dst, r.File[f].Name)
            if !strings.HasPrefix(dstpath, filepath.Clean(dst) + string(os.PathSeparator)) {
                return nil, fmt.Errorf("%s: illegal file path", src)
            }
            if r.File[f].FileInfo().IsDir() {
                if err := os.MkdirAll(dstpath, os.ModePerm); err != nil {
                    return nil, err
                }
            } else {
                if rc, err := r.File[f].Open(); err != nil {
                    return nil, err
                } else {
                    defer rc.Close()
                    if of, err := os.OpenFile(dstpath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, r.File[f].Mode()); err != nil {
                        return nil, err
                    } else {
                        defer of.Close()
                        if _, err = io.Copy(of, rc); err != nil {
                            return nil, err
                        } else {
                            of.Close()
                            rc.Close()
                            filenames = append(filenames, dstpath)
                        }
                    }
                }
            }
        }
        if len(filenames) == 0 {
            return nil, fmt.Errorf("zip file is empty")
        }
        return filenames, nil
    }
    

提交回复
热议问题