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 != nil {
        return err
    }
    defer r.Close()

    for _, f := range r.File {
        rc, err := f.Open()
        if err != nil {
            return err
        }
        defer rc.Close()

        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 f.Close()

            _, err = io.Copy(f, rc)
            if err != nil {
                return err
            }
        }
    }

    return nil
}
share|improve this question
3  
There is a problem with your code above - you are deferring the close of all the files in the for loop until Extract exits. This will work fine for small numbers of files but if you had 1000s in the zip then you'll run out of file descriptors. Factor the contents of the for loop to a function or closure to fix. – Nick Craig-Wood Dec 4 '13 at 8:05
    
I believe you also need os.MkdirAll(dest, 0755) right before your for loop. – Astockwell Jul 16 '14 at 23:28
up vote 30 down vote accepted

Slight rework of the OP's solution to create the containing directory dest if it doesn't exist, and to wrap the file extraction/writing in a closure to eliminate stacking of defer .Close() calls per @Nick Craig-Wood's comment:

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 descriptors issue with all the deferred .Close() methods
    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 {
            os.MkdirAll(filepath.Dir(path), f.Mode())
            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
}

Note: Updated to include Close() error handling as well (if we're looking for best practices, may as well follow ALL of them).

share|improve this answer
2  
Best answer. I really appreciate the closure. I have had an issue unzipping archives that have too many files. This solves that. – jabgibson Apr 9 '15 at 6:09
2  
This example would not work with zip files that had nested directories, since the output directory was never created. The code assumed that the directory had a separate entry, for example some/dir/ which could then be created, and after that some/dir/file.txt could be extracted in that. But the files are just listed alone with their full path (no separate directory entry). Which resulted in it failing because the directory was not created before trying to create the file in it. I edited the answer to fix this. – Joakim Aug 27 '16 at 10:24
    
This code breaks symbolic links when unpacking – Skywalker13 Jan 31 '17 at 13:13
    
My two cents framapic.org/WgZbcjkw7YM2/pxeWvDd8weuk – Skywalker13 Jan 31 '17 at 15:16
    
@Astockwell what is the use of if f.FileInfo().IsDir() { is it to check whether the file is a directory and if yes create it parent directories? if so why can't we use the code in else os.MkdirAll(filepath.Dir(path), f.Mode()) part alone for making parent directories? – Kasun Siyambalapitiya Sep 19 '17 at 12:58

I'm using archive/zip package to read .zip files and copy to the local disk. Below is the source code to unzip .zip files for my own needs.

import (
    "archive/zip"
    "io"
    "log"
    "os"
    "path/filepath"
    "strings"
)

func unzip(src, dest string) error {
    r, err := zip.OpenReader(src)
    if err != nil {
        return err
    }
    defer r.Close()

    for _, f := range r.File {
        rc, err := f.Open()
        if err != nil {
            return err
        }
        defer rc.Close()

        fpath := filepath.Join(dest, f.Name)
        if f.FileInfo().IsDir() {
            os.MkdirAll(fpath, f.Mode())
        } else {
            var fdir string
            if lastIndex := strings.LastIndex(fpath,string(os.PathSeparator)); lastIndex > -1 {
                fdir = fpath[:lastIndex]
            }

            err = os.MkdirAll(fdir, f.Mode())
            if err != nil {
                log.Fatal(err)
                return err
            }
            f, err := os.OpenFile(
                fpath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, f.Mode())
            if err != nil {
                return err
            }
            defer f.Close()

            _, err = io.Copy(f, rc)
            if err != nil {
                return err
            }
        }
    }
    return nil
}
share|improve this answer
1  
I was trying to use your code but it seems to have an error in the line if lastIndex := strings.LastIndex(fpath,string(os.PathSeparator)); lastIndex > -1 {. Where does strings come from? – lemavri Jul 10 '14 at 21:00
1  
Sorry, I left out the strings package. – swtdrgn Jul 11 '14 at 6:31
    
That explains it... thanks! – lemavri Jul 17 '14 at 22:07
    
strings.LastIndex(fpath,string(os.PathSeparator)) can replaced with filepath.Dir(fpath) – Joakim Aug 27 '16 at 10:14

I have been doing some browsing of google and repeatedly found people saying that there is no library that can handle that. Maybe I missed a custom repository in my search though and someone else will find it for us.

You may be able to make use of io.Copy(src, dest) to ease the process but I haven't tested it at all.

For instance:

os.MkDirAll(dest, r.File.Mode)
d, _ := os.Open(dest)
io.Copy(r.File, d)

Honestly to me your code looks pretty nice and if I were to do an Extract function myself (and the above doesn't work) then I would probably take a page from your book.

share|improve this answer

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)
    }
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.