easy way to unzip file with golang

后端 未结 8 774
情话喂你
情话喂你 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:27

    Every single answer on this page is wrong, as they all assume that the Zip archive will emit directory entries. Zip archives are not required to emit directory entries, and so given an archive such as that, a naive program will crash upon encountering the first non-root file, as no directories will ever be created, and the file creation will fail as the directory has not been created yet. Here is a different approach:

    package main
    
    import (
       "archive/zip"
       "os"
       "path"
    )
    
    func Unzip(source string) error {
       zip_o, e := zip.OpenReader(source)
       if e != nil {
          return e
       }
       for _, file_o := range zip_o.File {
          if file_o.Mode().IsDir() {
             continue
          }
          dir_s := path.Dir(file_o.Name)
          os.MkdirAll(dir_s, os.ModeDir)
          open_o, e := file_o.Open()
          if e != nil {
             return e
          }
          create_o, e := os.Create(file_o.Name)
          if e != nil {
             return e
          }
          create_o.ReadFrom(open_o)
       }
       return nil
    }
    

    Example use:

    package main
    import "log"
    
    func main() {
       e := Unzip("Microsoft.VisualCpp.Tools.HostX64.TargetX64.vsix")
       if e != nil {
          log.Fatal(e)
       }
    }
    

提交回复
热议问题