Use fastzip.NewArchiver to create an archiver instance. The archiver requires an io.Writer (like an *os.File) and a base directory path. For security, all archiving operations are restricted to occur within this specified directory.
To archive files, you must provide a map of os.FileInfo representing the files you wish to include. You can use filepath.Walk to build this map.
Key features:
- Preserves permissions, ownership (uid, gid on Linux/Unix), and modification times.
- Uses
github.com/klauspost/compress/flate by default for high performance. - Supports concurrent file archiving.
- Allows registering custom compressors via
RegisterCompressor.
// Create archive file
w, err := os.Create("archive.zip")
if err != nil {
panic(err)
}
defer w.Close()
// Create new Archiver
a, err := fastzip.NewArchiver(w, "~/fastzip-archiving")
if err != nil {
panic(err)
}
defer a.Close()
// Register a non-default level compressor if required
// a.RegisterCompressor(zip.Deflate, fastzip.FlateCompressor(1))
// Walk directory, adding the files we want to add
files := make(map[string]os.FileInfo)
if err = filepath.Walk("~/fastzip-archiving", func(pathname string, info os.FileInfo, err error) error {
files[pathname] = info
return nil
}); err != nil {
panic(err)
}
// Archive
if err = a.Archive(context.Background(), files); err != nil {
panic(err)
}