golang实现解压缩功能
func compress(file *os.File, prefix string, zw *zip.Writer) error {
info, err := file.Stat()
if err != nil {
slog.Error("解压压缩有误, " + err.Error())
return err
}
if info.IsDir() {
if prefix == "root" {
prefix = info.Name()
} else {
prefix = prefix + "/" + info.Name()
}
fileInfos, err := file.Readdir(-1)
if err != nil {
slog.Error("解压压缩有误, " + err.Error())
return err
}
for _, fi := range fileInfos {
f, err := os.Open(file.Name() + "/" + fi.Name())
if err != nil {
slog.Error("解压压缩有误, " + err.Error())
return err
}
err = compress(f, prefix, zw)
if err != nil {
slog.Error("解压压缩有误, " + err.Error())
return err
}
}
} else {
header, err := zip.FileInfoHeader(info)
if prefix == "root" {
header.Name = header.Name
} else {
header.Name = prefix + "/" + header.Name
}
if err != nil {
slog.Error("解压压缩有误, " + err.Error())
return err
}
writer, err := zw.CreateHeader(header)
if err != nil {
slog.Error("解压压缩有误, " + err.Error())
return err
}
_, err = io.Copy(writer, file)
file.Close()
if err != nil {
slog.Error("解压压缩有误, " + err.Error())
return err
}
}
return nil
}
func Compress(files []*os.File, dest string) error {
d, _ := os.Create(dest)
defer d.Close()
w := zip.NewWriter(d)
defer w.Close()
for _, file := range files {
err := compress(file, "root", w)
if err != nil {
slog.Error("解压压缩有误, " + err.Error())
return err
}
}
return nil
}