用服务器自带的unzip命令解压zip包时,经常遇到编码问题,所以用Go写一个zip解压 脚本 来处理zip包
代码如下:
package main
import (
"archive/zip"
"bytes"
"flag"
"fmt"
" io "
"io/ioutil"
"log"
"os"
"path/filepath"
"golang.org/x/text/encoding/simplifiedchinese"
" go lang.org/x/text/transform"
)
func unzip(zipFile string, destDir string) error {
zipReader, err := zip.OpenReader(zipFile)
if err != nil {
return err
}
defer zipReader. Close ()
var decodeName string
for _, f := range zipReader.File {
if f. Flags == 0 {
i := byte s.NewReader([]byte(f.Name))
decoder := transform.NewReader(i, simplifiedchinese.GB18030.NewDecoder())
content, _ := ioutil.ReadAll(decoder)
decodeName = string(content)
} else {
decodeName = f.Name
}
fpath := filepath.Join(destDir, decodeName)
if f.FileInfo().IsDir() {
os.MkdirAll(fpath, os.ModePerm)
} else {
if err = os.MkdirAll(filepath.Dir(fpath), os.ModePerm); err != nil {
return err
}
inFile, err := f.Open()
if err != nil {
return err
}
defer inFile.Close()
outFile, err := os.OpenFile(fpath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, f.Mode())
if err != nil {
return err
}
defer outFile.Close()
_, err = io.Copy(outFile, inFile)
if err != nil {
return err
}
}
}
return nil
}
var (
src string
dst string
)
func usage() {
fmt.Fprintf(os.Stderr, `gounzip version: gounzip/1.0
Usage:
gounzip --src='/mnt/a.zip' --dst='/ tmp '
gounzip --src '/mnt/a.zip' --dst '/tmp'
gounzip -src='/mnt/a.zip' -dst='/tmp'
gounzip -src '/mnt/a.zip' -dst '/tmp'
Options:
`)
flag.PrintDefaults()
}
func init() {
flag.StringVar(&src, "src", "", "zip file ")
flag.StringVar(&dst, "dst", "/tmp", "unzip dir")
flag.Usage = usage
flag.Parse()
}
func main() {
err := unzip(src, dst)
if err != nil {
log.Println(err)
}
}
编译后放到bin目录下
查看帮助:

这里命令行,简单实用了flag,可以用cobra库来替代,优化命令行