The
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 and will not add the. zip extension func compress (frm, DST string) error {buf: = bytes to DST. Newbuffer ([]byte, 0, 10*1024*1024)]//Create a read-write buffer myzip: = zip. Newwriter (BUF)//with a compressor to wrap the buffer///Use the Walk method to write the files in all directories to 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 file information to zip format if err!= nil {return filepath. Skipdir} header. Name, _ = filepath. Rel (filepath. Dir (frm), path) if!info. Isdir () {//Determine the compression algorithm used (this is the built-in registered deflate) header. Method = 8 file, err = Ioutil. ReadFile (path)//Get the file content if Err!= nil {return filepath. Skipdir}} else {file = nil}//the above section ifAll errors return filepath. Skipdir//below if errors are returned directly to the error//purpose is to compress the files in the directory as much as possible while ensuring that the zip file is in the correct format w, err: = Myzip. CreateHeader (header)//Create a record and write file information if Err!= nil {return Err} _, Err = w.write (file)//non directory file writes data. The directory will not write data if Err!= nil {//Because the contents of the catalog may be modified return err//The key is I don't know how to get the contents of the directory file} return nil}) if Err!= nil {return err} myzip. Close ()//Shut down the compressor so that data in the compressor buffer is written to buf file, err: = OS. Create (DST)//Create a ZIP file if err!= nil {return err} defer file. Close () _, err = buf.
WriteTo (file)//writes the data in BUF to the file if Err!= nil {return err}
The above is the entire contents of this article, I hope you can enjoy.