zip
packagestandard libraryThis package is not in the latest version of its module.
Details
Validgo.mod file
The Go module system was introduced in Go 1.11 and is the official dependency management solution for Go.
Redistributable license
Redistributable licenses place minimal restrictions on how software can be used, modified, and redistributed.
Tagged version
Modules with tagged versions give importers more predictable builds.
Stable version
When a project reaches major version v1 it is considered stable.
- Learn more about best practices
Repository
Links
Documentation¶
Overview¶
Package zip provides support for reading and writing ZIP archives.
See theZIP specification for details.
This package does not support disk spanning.
A note about ZIP64:
To be backwards compatible the FileHeader has both 32 and 64 bit Sizefields. The 64 bit fields will always contain the correct value andfor normal archives both fields will be the same. For files requiringthe ZIP64 format the 32 bit fields will be 0xffffffff and the 64 bitfields must be used instead.
Index¶
- Constants
- Variables
- func RegisterCompressor(method uint16, comp Compressor)
- func RegisterDecompressor(method uint16, dcomp Decompressor)
- type Compressor
- type Decompressor
- type File
- type FileHeader
- type ReadCloser
- type Reader
- type Writer
- func (w *Writer) AddFS(fsys fs.FS) error
- func (w *Writer) Close() error
- func (w *Writer) Copy(f *File) error
- func (w *Writer) Create(name string) (io.Writer, error)
- func (w *Writer) CreateHeader(fh *FileHeader) (io.Writer, error)
- func (w *Writer) CreateRaw(fh *FileHeader) (io.Writer, error)
- func (w *Writer) Flush() error
- func (w *Writer) RegisterCompressor(method uint16, comp Compressor)
- func (w *Writer) SetComment(comment string) error
- func (w *Writer) SetOffset(n int64)
Examples¶
Constants¶
const (Storeuint16 = 0// no compressionDeflateuint16 = 8// DEFLATE compressed)
Compression methods.
Variables¶
Functions¶
funcRegisterCompressor¶added ingo1.2
func RegisterCompressor(methoduint16, compCompressor)
RegisterCompressor registers custom compressors for a specified method ID.The common methodsStore andDeflate are built in.
funcRegisterDecompressor¶added ingo1.2
func RegisterDecompressor(methoduint16, dcompDecompressor)
RegisterDecompressor allows custom decompressors for a specified method ID.The common methodsStore andDeflate are built in.
Types¶
typeCompressor¶added ingo1.2
type Compressor func(wio.Writer) (io.WriteCloser,error)
A Compressor returns a new compressing writer, writing to w.The WriteCloser's Close method must be used to flush pending data to w.The Compressor itself must be safe to invoke from multiple goroutinessimultaneously, but each returned writer will be used only byone goroutine at a time.
typeDecompressor¶added ingo1.2
type Decompressor func(rio.Reader)io.ReadCloser
A Decompressor returns a new decompressing reader, reading from r.Theio.ReadCloser's Close method must be used to release associated resources.The Decompressor itself must be safe to invoke from multiple goroutinessimultaneously, but each returned reader will be used only byone goroutine at a time.
typeFile¶
type File struct {FileHeader// contains filtered or unexported fields}
A File is a single file in a ZIP archive.The file information is in the embeddedFileHeader.The file content can be accessed by callingFile.Open.
func (*File)DataOffset¶added ingo1.2
DataOffset returns the offset of the file's possibly-compresseddata, relative to the beginning of the zip file.
Most callers should instead useFile.Open, which transparentlydecompresses data and verifies checksums.
func (*File)Open¶
func (f *File) Open() (io.ReadCloser,error)
Open returns aReadCloser that provides access to theFile's contents.Multiple files may be read concurrently.
typeFileHeader¶
type FileHeader struct {// Name is the name of the file.//// It must be a relative path, not start with a drive letter (such as "C:"),// and must use forward slashes instead of back slashes. A trailing slash// indicates that this file is a directory and should have no data.Namestring// Comment is any arbitrary user-defined string shorter than 64KiB.Commentstring// NonUTF8 indicates that Name and Comment are not encoded in UTF-8.//// By specification, the only other encoding permitted should be CP-437,// but historically many ZIP readers interpret Name and Comment as whatever// the system's local character encoding happens to be.//// This flag should only be set if the user intends to encode a non-portable// ZIP file for a specific localized region. Otherwise, the Writer// automatically sets the ZIP format's UTF-8 flag for valid UTF-8 strings.NonUTF8boolCreatorVersionuint16ReaderVersionuint16Flagsuint16// Method is the compression method. If zero, Store is used.Methoduint16// Modified is the modified time of the file.//// When reading, an extended timestamp is preferred over the legacy MS-DOS// date field, and the offset between the times is used as the timezone.// If only the MS-DOS date is present, the timezone is assumed to be UTC.//// When writing, an extended timestamp (which is timezone-agnostic) is// always emitted. The legacy MS-DOS date field is encoded according to the// location of the Modified time.Modifiedtime.Time// ModifiedTime is an MS-DOS-encoded time.//// Deprecated: Use Modified instead.ModifiedTimeuint16// ModifiedDate is an MS-DOS-encoded date.//// Deprecated: Use Modified instead.ModifiedDateuint16// CRC32 is the CRC32 checksum of the file content.CRC32uint32// CompressedSize is the compressed size of the file in bytes.// If either the uncompressed or compressed size of the file// does not fit in 32 bits, CompressedSize is set to ^uint32(0).//// Deprecated: Use CompressedSize64 instead.CompressedSizeuint32// UncompressedSize is the uncompressed size of the file in bytes.// If either the uncompressed or compressed size of the file// does not fit in 32 bits, UncompressedSize is set to ^uint32(0).//// Deprecated: Use UncompressedSize64 instead.UncompressedSizeuint32// CompressedSize64 is the compressed size of the file in bytes.CompressedSize64uint64// UncompressedSize64 is the uncompressed size of the file in bytes.UncompressedSize64uint64Extra []byteExternalAttrsuint32// Meaning depends on CreatorVersion}
FileHeader describes a file within a ZIP file.See theZIP specification for details.
funcFileInfoHeader¶
func FileInfoHeader(fifs.FileInfo) (*FileHeader,error)
FileInfoHeader creates a partially-populatedFileHeader from anfs.FileInfo.Because fs.FileInfo's Name method returns only the base name ofthe file it describes, it may be necessary to modify the Name fieldof the returned header to provide the full path name of the file.If compression is desired, callers should set the FileHeader.Methodfield; it is unset by default.
func (*FileHeader)FileInfo¶
func (h *FileHeader) FileInfo()fs.FileInfo
FileInfo returns an fs.FileInfo for theFileHeader.
func (*FileHeader)ModTimedeprecated
func (h *FileHeader) ModTime()time.Time
ModTime returns the modification time in UTC using the legacy[ModifiedDate] and [ModifiedTime] fields.
Deprecated: Use [Modified] instead.
func (*FileHeader)Mode¶
func (h *FileHeader) Mode() (modefs.FileMode)
Mode returns the permission and mode bits for theFileHeader.
func (*FileHeader)SetModTimedeprecated
func (h *FileHeader) SetModTime(ttime.Time)
SetModTime sets the [Modified], [ModifiedTime], and [ModifiedDate] fieldsto the given time in UTC.
Deprecated: Use [Modified] instead.
func (*FileHeader)SetMode¶
func (h *FileHeader) SetMode(modefs.FileMode)
SetMode changes the permission and mode bits for theFileHeader.
typeReadCloser¶
type ReadCloser struct {Reader// contains filtered or unexported fields}
A ReadCloser is aReader that must be closed when no longer needed.
funcOpenReader¶
func OpenReader(namestring) (*ReadCloser,error)
OpenReader will open the Zip file specified by name and return a ReadCloser.
If any file inside the archive uses a non-local name(as defined byfilepath.IsLocal) or a name containing backslashesand the GODEBUG environment variable contains `zipinsecurepath=0`,OpenReader returns the reader with an ErrInsecurePath error.A future version of Go may introduce this behavior by default.Programs that want to accept non-local names can ignorethe ErrInsecurePath error and use the returned reader.
func (*ReadCloser)Close¶
func (rc *ReadCloser) Close()error
Close closes the Zip file, rendering it unusable for I/O.
typeReader¶
A Reader serves content from a ZIP archive.
Example¶
package mainimport ("archive/zip""fmt""io""log""os")func main() {// Open a zip archive for reading.r, err := zip.OpenReader("testdata/readme.zip")if err != nil {log.Fatal(err)}defer r.Close()// Iterate through the files in the archive,// printing some of their contents.for _, f := range r.File {fmt.Printf("Contents of %s:\n", f.Name)rc, err := f.Open()if err != nil {log.Fatal(err)}_, err = io.CopyN(os.Stdout, rc, 68)if err != nil {log.Fatal(err)}rc.Close()fmt.Println()}}
Output:Contents of README:This is the source code repository for the Go programming language.
funcNewReader¶
NewReader returns a newReader reading from r, which is assumed tohave the given size in bytes.
If any file inside the archive uses a non-local name(as defined byfilepath.IsLocal) or a name containing backslashesand the GODEBUG environment variable contains `zipinsecurepath=0`,NewReader returns the reader with anErrInsecurePath error.A future version of Go may introduce this behavior by default.Programs that want to accept non-local names can ignoretheErrInsecurePath error and use the returned reader.
func (*Reader)Open¶added ingo1.16
Open opens the named file in the ZIP archive,using the semantics of fs.FS.Open:paths are always slash separated, with noleading / or ../ elements.
func (*Reader)RegisterDecompressor¶added ingo1.6
func (r *Reader) RegisterDecompressor(methoduint16, dcompDecompressor)
RegisterDecompressor registers or overrides a custom decompressor for aspecific method ID. If a decompressor for a given method is not found,Reader will default to looking up the decompressor at the package level.
typeWriter¶
type Writer struct {// contains filtered or unexported fields}
Writer implements a zip file writer.
Example¶
package mainimport ("archive/zip""bytes""log")func main() {// Create a buffer to write our archive to.buf := new(bytes.Buffer)// Create a new zip archive.w := zip.NewWriter(buf)// Add some files to the archive.var files = []struct {Name, Body string}{{"readme.txt", "This archive contains some text files."},{"gopher.txt", "Gopher names:\nGeorge\nGeoffrey\nGonzo"},{"todo.txt", "Get animal handling licence.\nWrite more examples."},}for _, file := range files {f, err := w.Create(file.Name)if err != nil {log.Fatal(err)}_, err = f.Write([]byte(file.Body))if err != nil {log.Fatal(err)}}// Make sure to check the error on Close.err := w.Close()if err != nil {log.Fatal(err)}}
func (*Writer)AddFS¶added ingo1.22.0
AddFS adds the files from fs.FS to the archive.It walks the directory tree starting at the root of the filesystemadding each file to the zip using deflate while maintaining the directory structure.
func (*Writer)Close¶
Close finishes writing the zip file by writing the central directory.It does not close the underlying writer.
func (*Writer)Copy¶added ingo1.17
Copy copies the file f (obtained from aReader) into w. It copies the rawform directly bypassing decompression, compression, and validation.
func (*Writer)Create¶
Create adds a file to the zip file using the provided name.It returns aWriter to which the file contents should be written.The file contents will be compressed using theDeflate method.The name must be a relative path: it must not start with a driveletter (e.g. C:) or leading slash, and only forward slashes areallowed. To create a directory instead of a file, add a trailingslash to the name. Duplicate names will not overwrite previous entriesand are appended to the zip file.The file's contents must be written to theio.Writer before the nextcall toWriter.Create,Writer.CreateHeader, orWriter.Close.
func (*Writer)CreateHeader¶
func (w *Writer) CreateHeader(fh *FileHeader) (io.Writer,error)
CreateHeader adds a file to the zip archive using the providedFileHeaderfor the file metadata.Writer takes ownership of fh and may mutateits fields. The caller must not modify fh after callingWriter.CreateHeader.
This returns aWriter to which the file contents should be written.The file's contents must be written to the io.Writer before the nextcall toWriter.Create,Writer.CreateHeader,Writer.CreateRaw, orWriter.Close.
func (*Writer)CreateRaw¶added ingo1.17
func (w *Writer) CreateRaw(fh *FileHeader) (io.Writer,error)
CreateRaw adds a file to the zip archive using the providedFileHeader andreturns aWriter to which the file contents should be written. The file'scontents must be written to the io.Writer before the next call toWriter.Create,Writer.CreateHeader,Writer.CreateRaw, orWriter.Close.
In contrast toWriter.CreateHeader, the bytes passed to Writer are not compressed.
CreateRaw's argument is stored in w. If the argument is a pointer to the embeddedFileHeader in aFile obtained from aReader created from in-memory data,then w will refer to all of that memory.
func (*Writer)Flush¶added ingo1.4
Flush flushes any buffered data to the underlying writer.Calling Flush is not normally necessary; calling Close is sufficient.
func (*Writer)RegisterCompressor¶added ingo1.6
func (w *Writer) RegisterCompressor(methoduint16, compCompressor)
RegisterCompressor registers or overrides a custom compressor for a specificmethod ID. If a compressor for a given method is not found,Writer willdefault to looking up the compressor at the package level.
Example¶
package mainimport ("archive/zip""bytes""compress/flate""io")func main() {// Override the default Deflate compressor with a higher compression level.// Create a buffer to write our archive to.buf := new(bytes.Buffer)// Create a new zip archive.w := zip.NewWriter(buf)// Register a custom Deflate compressor.w.RegisterCompressor(zip.Deflate, func(out io.Writer) (io.WriteCloser, error) {return flate.NewWriter(out, flate.BestCompression)})// Proceed to add files to w.}
func (*Writer)SetComment¶added ingo1.10
SetComment sets the end-of-central-directory comment field.It can only be called beforeWriter.Close.