1 Star 0 Fork 0

h79/goutils

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
gzip.go 1.28 KB
一键复制 编辑 原始数据 按行查看 历史
huqiuyun 提交于 2023-09-03 16:54 . 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 {
return a.gw.Close()
}
// 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 file.Close()
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
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/h79/goutils.git
git@gitee.com:h79/goutils.git
h79
goutils
goutils
v1.9.15

搜索帮助