This is a creation in Article, where the information may have evolved or changed.
The Archive/zip package provides read and write operations for the ZIP archive file.
Before you introduce the ZIP package, let's explain the difference between zip and tar.
Both files are archived and not compressed. And the use of different platforms, for the Windows platform, the most commonly used format is zip and rar, most of the domestic use of RAR, most of the foreign zip. For Unix-like platforms, the commonly used format is tar and tar.gz,zip less, and RAR has little.
Zip format is open and free, so widely used in Windows, Linux, MacOS platform, to say zip has any shortcomings, that is, it is not very high compression ratio, such as RAR and tar.gz format.
Strictly speaking, tar is only a packaging format, does not compress the file, mainly for the sake of the management of the file, so the size of the document is generally much larger than zip and tar.gz, but this format also has obvious advantages, such as packaging speed is very fast, packaging, CPU usage is also very low, Because there is no need for compression.
The ZIP package is then explained.
Zip package does not support operation across hard disks in order to be backwards compatible, Fileheader has both 32-bit and 64-bit size fields. 64-bit fields always contain the correct values, and the values are the same for normal format files without seeing them. The 32-bit field for the archive file in ZIP64 format will be 0xffffffff and must use a 64-bit field.
Constants
Compression algorithm
Const ( Store uint16 = 0 Deflate uint16 = 8)
Variables
Error variable
var ( errformat = errors. New ("Zip:not a valid zip file") erralgorithm = errors. New ("zip:unsupported compression algorithm") errchecksum = errors. New ("Zip:checksum error") func_name)
Func Registercompressor (Method uint16, Comp Compressor)//uses the specified method ID to generate a Compressor type function. Common methods store and deflate are built-in
Func Registerdecompressor (Method uint16, D decompressor)//A function that registers a decompressor type with the specified method ID
Type Compressor
Type Compressor func (IO. Writer) (IO. Writecloser, error)
The compressor function type returns a io.writecloser that compresses the data after it is written to the provided interface. When off, the data in the cache should be written to the downlevel interface.
Type decompressor
Type decompressor func (IO. Reader) io. Readcloser
The decompressor function type will wrap a io.reader into a io.Reader.Decompressor function type with decompressing properties and return a io.readcloser, the Read method of which reads the data fetched from the provided interface in advance Compression. You need to close the IO at the end of the read. Readcloser.
Type File
Type File struct { fileheader //contains filtered or unexported fields}
Func (f *file) Dataoffset (offset int64, err error)//dataoffset returns the offset of the file's potentially existing compressed data relative to the start of the zip file. Most callers should use open instead, which will actively decompress the data and validate the checksum.
Func (f *file) Open () (RC io. Readcloser, err Error) The//open method returns a Io.readcloser interface that provides a way to read the contents of a file. Multiple files can be read at the same time.
Type Fileheader
Type Fileheader struct { name string //name is a file name, it must be a relative path, cannot start with a device or slash, only accept '/' as the path delimiter creatorversion UInt16 readerversion uint16 Flags uint16 Method uint16 modifiedtime uint16 // MS-DOS time ModifiedDate uint16//MS-dos date CRC32 uint32 compressedsize uint32// Deprecated Use CompressedSize64 uncompressedsize uint32//deprecated; use UncompressedSize64 CompressedSize64 UInt64 UncompressedSize64 UInt64 Extra []byte externalattrs uint32//meaning depends on creatorversion Comment String}
Func Fileinfoheader (fi os. FileInfo) (*fileheader, error)//fileinfoheader returns a header that fills in some fields based on FI. Because the OS. The name method of the FileInfo interface only returns the pathname of the file it describes, and it may be necessary to modify the name field of the return value to the full pathname of the file.
Func (H *fileheader) FileInfo () OS. FileInfo//fileinfo Returns a os.fileinfo generated based on the information of H.
Func (H *fileheader) modtime () time. Time//Get last Modified
Func (H *fileheader) mode () (Mode OS. FileMode)//mode returns the permission and mode bits of H.
Func (H *fileheader) setmodtime (t time. Time)//set Change times
Func (H *fileheader) setmode (mode OS. FileMode)//Set mode
An example of how to use it
Package Mainimport ("Archive/zip" "FMT" "OS" "Time") Func main () {FileInfo, err: = OS. Stat (".. /1.txt ") if err! = Nil {fmt. PRINTLN (Err)}fileheader, err: = Zip. Fileinfoheader (FileInfo) if err! = Nil {fmt. PRINTLN (Err)}fmt. Println (Fileheader. Modtime ())//2015-09-22 15:55:02 +0000 utcfileheader.setmodtime (time. Now (). Adddate (1, 1, 1)) fmt. Println (Fileheader. Modtime ())//2016-12-11 06:57:48 +0000 UTC}
Type Readcloser
Type readcloser struct { Reader //contains filtered or unexported fields}
Func openreader (name string) (*readcloser, error)//Opens a file that specifies a zip type named name, and returns a Readcloser
Func (RC *readcloser) Close () error//close Readcloser
Type Reader
Type Reader struct { File []*file Comment string //contains filtered or unexported fields}
Func newreader (R io. Readerat, size Int64) (*reader, error)//newreader returns a *reader,r that reads data from R is assumed to be of size byte.
Type writer//write to implement ZIP file
Type Writer struct { cw *countwriter dir []*header last *filewriter closed bool }
Func newwriter (w io. Writer) *writer//newwriter creates and returns a *writer that writes a zip file to W
Func (w *writer) Close () error//close Writer W
Func (w *writer) Create (name string) (IO. Writer, error)//use the given filename to add a file into the zip file. This method returns an IO. Writer interface (used to write the contents of the newly added file). The file name must be a relative path and cannot start with a device or slash, only accept '/' as a path delimited. The contents of the new file must be written all before the next call to the CreateHeader, create, or Close method.
Func (w *writer) CreateHeader (FH *fileheader) (IO. Writer, error)//Use the given *fileheader to add a file into the zip file as the metadata for the file. This method returns an IO. Writer interface (used to write the contents of the newly added file). The contents of the new file must be written all before the next call to the CreateHeader, create, or Close method.
Func (w *writer) flush () error//writes the cached data to the underlying IO, normally calling Flush is not necessary, and calling close is necessary.
Func (w *writer) SetOffset (n Int64)//This function is used to set the start offset of writing the zip data to the underlying writer, which is often used to append a zip file to the back of a file, such as after writing a data into a binary data, The function must be called before the data is written.
Illustrate the use of the zip reader and writer.
Package Mainimport ( "Archive/zip" "FMT" "IO" "Io/ioutil" "OS" "Time") Func main () { compresszip () //Compression decompresszip ()//Decompression}func compresszip () { const dir = ". /img-50/" //get the source file list f, err: = Ioutil. ReadDir (dir) if err! = Nil { fmt. PRINTLN (Err) } fzip, _: = OS. Create ("Img-50.zip") w: = Zip. Newwriter (fzip) defer w.close () for _, File: = range f { & nbsp  FW, _: = W.create (file. Name ()) filecontent, err: = Ioutil. ReadFile (dir + file. Name ()) if Err! = Nil { Fmt. PRINTLN (ERR) } n, err: = FW. Write (filecontent) if Err! = Nil {  FMT. PRINTLN (Err) } fmt. PRINTLN (n) }}func decompresszip () { const File = "Img-50.zip" Const DIR = "img/" os. Mkdir (dir, 0777)//Create a directory  CF, err: = Zip. Openreader (file)//read zip file if err! = Nil { fmt. PRINTLN (Err) } defer cf. Close () for _, File: = Range cf. File { rc, err: = file. Open () if Err! = Nil { fmt . PRINTLN (Err) } f, ERR: = OS. Create (dir + file. Name) if Err! = Nil { fmt. PRINTLN (Err) } defer f.close () n, err: = Io. Copy (f, rc) if Err! = Nil { fmt. PRINTLN (Err) } fmt. PRINTLN (n) }}
Reference: https://golang.org/pkg/archive/zip/
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.