I want to zip some directory inside content into zip file
e.g. assume i’ve this directory structure
dir1
file1.html
file2.go
Now I want to zip it to dir1.zip
which is working
when I extract it I got the same structure...
I want to zip the content inside that when I unzip it I get the files inside without the `dir1' folder as root after extracting it
file1.html
file2.go
I try to play with the path’s with this code and it doesn’t work,
Any idea what I miss here ?
i've tryied
func Zipit(source, target string) error {
zipfile, err := os.Create(target)
if err != nil {
return err
}
defer zipfile.Close()
archive := zip.NewWriter(zipfile)
defer archive.Close()
info, err := os.Stat(source)
if err != nil {
return nil
}
var baseDir string
if info.IsDir() {
baseDir = filepath.Base(source)
}
filepath.Walk(source, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
header, err := zip.FileInfoHeader(info)
if err != nil {
return err
}
if baseDir != "" {
header.Name = filepath.Join(baseDir, strings.TrimPrefix(path, source))
}
if info.IsDir() {
header.Name += "/"
} else {
header.Method = zip.Deflate
}
writer, err := archive.CreateHeader(header)
if err != nil {
return err
}
if info.IsDir() {
return nil
}
file, err := os.Open(path)
if err != nil {
return err
}
defer file.Close()
_, err = io.Copy(writer, file)
return err
})
return err
}
dir.Zipit("path/dir1" +"/", "test"+".zip")
Or maybe there is simpler way in GO to achieve this?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…