1 Star 0 Fork 0

h79 / goutils

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
gzip.go 1.40 KB
一键复制 编辑 原始数据 按行查看 历史
huqiuyun 提交于 2024-04-01 18:55 . build
// Package gzip implements the Archive interface providing gz archiving
// and compression.
package gzip
import (
"fmt"
fileconfig "gitee.com/h79/goutils/common/file/config"
"io"
"os"
gzip "github.com/klauspost/pgzip"
)
// Archive as gz.
type Archive struct {
gw *gzip.Writer
}
// New gz archive.
func New(target io.Writer) Archive {
// the error will be nil since the compression level is valid
gw, _ := gzip.NewWriterLevel(target, gzip.BestCompression)
return Archive{
gw: gw,
}
}
// Close all closeables.
func (a Archive) Close() error {
if a.gw != nil {
err := a.gw.Close()
a.gw = nil
return err
}
return nil
}
// Add file to the archive.
func (a Archive) Add(f fileconfig.File, stream ...fileconfig.ReaderStream) error {
if a.gw.Header.Name != "" {
return fmt.Errorf("gzip: failed to add %s, only one file can be archived in gz format", f.Destination)
}
file, err := os.Open(f.Source) // #nosec
if err != nil {
return err
}
defer func(file *os.File) {
err = file.Close()
if err != nil {
}
}(file)
info, err := file.Stat()
if err != nil {
return err
}
if info.IsDir() {
return nil
}
a.gw.Header.Name = f.Destination
if f.Info.ParsedMTime.IsZero() {
a.gw.Header.ModTime = info.ModTime()
} else {
a.gw.Header.ModTime = f.Info.ParsedMTime
}
if _, err = io.Copy(a.gw, file); err != nil {
return err
}
for i := range stream {
stream[i].OnReader(file)
}
return nil
}
Go
1
https://gitee.com/h79/goutils.git
git@gitee.com:h79/goutils.git
h79
goutils
goutils
v1.20.57

搜索帮助

53164aa7 5694891 3bd8fe86 5694891