用户下载数据时,将数据打包成zip包,并给zip包添加上密码。

测试数据如下:

d405209bf992d28f2a64f4cd87632811.png

处理:

1788003a74be2761287550991b9db44d.png

完整代码如下:

package mainimport ("archive/zip""io""log""os""path/filepath""strings"ezip "github.com/alexmullins/zip")func main() {if err := EncryptZip("./data", "./example.zip", "golang"); err != nil {log.Fatal(err)}}// src can be a single file or a directoryfunc EncryptZip(src, dst, passwd string) error {zipfile, err := os.Create(dst)if err != nil {return err}defer zipfile.Close()archive := ezip.NewWriter(zipfile)defer archive.Close()filepath.Walk(src, func(path string, info os.FileInfo, err error) error {if err != nil {return err}header, err := ezip.FileInfoHeader(info)if err != nil {return err}header.Name = strings.TrimPrefix(path, filepath.Dir(src)+"/")if info.IsDir() {header.Name += "/"} else {header.Method = zip.Deflate}// 设置密码header.SetPassword(passwd)writer, err := archive.CreateHeader(header)if err != nil {return err}if !info.IsDir() {file, err := os.Open(path)if err != nil {return err}defer file.Close()_, err = io.Copy(writer, file)}return err})return err}

解压:

620c591abeb74f3e27bcbadd64358fc5.png