前端之家收集整理的这篇文章主要介绍了
通过接口实现压缩文件、目录,修正遍历方式,未添加排除文件操作,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
package zip
import (
"io"
"os"
"path/filepath"
"strings"
)
type Compress interface {
Close() error
WriteHead(path string,info os.FileInfo) error
Write(p []byte) (int,error)
}
func walk(path string,compresser Compress) error {
info,err := os.Lstat(path)
if err != nil {
return err
}
var baseDir string
if info.IsDir() {
baseDir = filepath.Base(path)
}
filepath.Walk(path,func(root string,info os.FileInfo,err error) error {
if err != nil {
return err
}
root = strings.Replace(root,"\\","/",-1)
fileroot := root
if root = strings.TrimPrefix(root,path); root == "" {
root = baseDir
}
err = compresser.WriteHead(root,info)
if err != nil {
return nil
}
F,err := os.Open(fileroot)
if err != nil {
return nil
}
io.Copy(compresser,F)
F.Close()
return nil
})
return nil
}
@H_
502_2@
package zip
import (
"archive/tar"
"compress/gzip"
"os"
)
type TgzWirter struct {
tar *tar.Writer
gz *gzip.Writer
}
func NewTgzWirter(File *os.File) *TgzWirter {
gw := gzip.NewWriter(File)
tw := tar.NewWriter(gw)
return &TgzWirter{tw,gw}
}
func (self *TgzWirter) Close() error {
self.tar.Close()
return self.gz.Close()
}
func (self *TgzWirter) WriteHead(path string,info os.FileInfo) error {
if path == "." || path == ".." {
return nil
}
head,err := tar.FileInfoHeader(info,"")
if err != nil {
return err
}
head.Name = path
if info.IsDir() {
head.Name += "/"
}
return self.tar.WriteHeader(head)
}
func (self *TgzWirter) Write(p []byte) (int,error) {
return self.tar.Write(p)
}
func (self *TgzWirter) Walk(source string) error {
return walk(source,self)
}
@H_
502_2@
package zip
import (
"archive/zip"
"io"
"os"
"time"
)
func NewZipWriter(File *os.File) *ZipWrite {
zipwrite := zip.NewWriter(File)
return &ZipWrite{zone: 8,zw: zipwrite,file: File}
}
type ZipWrite struct {
zone int64
zw *zip.Writer
writer io.Writer
file *os.File
}
func (self *ZipWrite) Close() error {
return self.zw.Close()
}
func (self *ZipWrite) WriteHead(path string,err := zip.FileInfoHeader(info)
if err != nil {
return err
}
if !info.IsDir() {
head.Method = zip.Deflate
}
head.Name = path
if info.IsDir() {
head.Name += "/"
}
head.SetModTime(time.Unix(info.ModTime().Unix()+self.zone*60*60,0))
write,err := self.zw.CreateHeader(head)
if err != nil {
return err
}
self.writer = write
return nil
}
func (self *ZipWrite) Write(p []byte) (int,error) {
return self.writer.Write(p)
}
func (self *ZipWrite) Walk(source string) error {
return walk(source,self)
}
原文链接:https://www.f2er.com/go/189896.html