go language production of zip compression program
- 2020-05-27 05:53:06
- OfStack
You can compress files and directories.
package main
import (
"archive/zip"
"bytes"
"fmt"
"io/ioutil"
"os"
"path/filepath"
)
func main() {
if err := compress(`gopkg`, `gopkg.zip`); err != nil {
fmt.Println(err)
}
}
// parameter frm Can be a file or directory, not given dst add .zip extension
func compress(frm, dst string) error {
buf := bytes.NewBuffer(make([]byte, 0, 10*1024*1024)) // create 1 Individual read-write buffer
myzip := zip.NewWriter(buf) // Wrap the buffer with a compressor
// with Walk Method to write to all files in a directory zip
err := filepath.Walk(frm, func(path string, info os.FileInfo, err error) error {
var file []byte
if err != nil {
return filepath.SkipDir
}
header, err := zip.FileInfoHeader(info) // convert zip Format file information
if err != nil {
return filepath.SkipDir
}
header.Name, _ = filepath.Rel(filepath.Dir(frm), path)
if !info.IsDir() {
// Determine the compression algorithm to use (this is a built-in registration deflate )
header.Method = 8
file, err = ioutil.ReadFile(path) // Get file content
if err != nil {
return filepath.SkipDir
}
} else {
file = nil
}
// The top part returns if something goes wrong filepath.SkipDir
// The following sections return the error if it occurs
// The purpose is to compress the files under the directory as much as possible, while ensuring that zip File format correct
w, err := myzip.CreateHeader(header) // create 1 Record and write file information
if err != nil {
return err
}
_, err = w.Write(file) // Non-directory files write data, and directories do not write data
if err != nil { // Because the contents of the directory may change
return err // The most important thing is that I don't know how to get the contents of the directory files
}
return nil
})
if err != nil {
return err
}
myzip.Close() // Close the compressor and let the data in the compressor buffer be written buf
file, err := os.Create(dst) // To establish zip file
if err != nil {
return err
}
defer file.Close()
_, err = buf.WriteTo(file) // will buf Is written to a file
if err != nil {
return err
}
return nil
}
That's all for this article, I hope you enjoy it.