package zipImport Patharchive/zip (on go.dev)Dependency Relation
imports 17 packages, and imported by 0 packages
Involved Source Filesreader.goregister.go Package zip provides support for reading and writing ZIP archives.
See the [ZIP 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 Size
fields. The 64 bit fields will always contain the correct value and
for normal archives both fields will be the same. For files requiring
the ZIP64 format the 32 bit fields will be 0xffffffff and the 64 bit
fields must be used instead.writer.go
Code Examples
package main
import (
"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()
}
}
package main
import (
"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)
}
}
package main
import (
"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.
}
Package-Level Type Names (total 7)
/* sort by: | */
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 goroutines
simultaneously, but each returned writer will be used only by
one goroutine at a time.
func RegisterCompressor(method uint16, comp Compressor)
func (*Writer).RegisterCompressor(method uint16, comp Compressor)
A Decompressor returns a new decompressing reader, reading from r.
The [io.ReadCloser]'s Close method must be used to release associated resources.
The Decompressor itself must be safe to invoke from multiple goroutines
simultaneously, but each returned reader will be used only by
one goroutine at a time.
func RegisterDecompressor(method uint16, dcomp Decompressor)
func (*Reader).RegisterDecompressor(method uint16, dcomp Decompressor)
A File is a single file in a ZIP archive.
The file information is in the embedded [FileHeader].
The file content can be accessed by calling [File.Open].FileHeaderFileHeader CRC32 is the CRC32 checksum of the file content. Comment is any arbitrary user-defined string shorter than 64KiB. 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. CompressedSize64 is the compressed size of the file in bytes.FileHeader.CreatorVersionuint16 // Meaning depends on CreatorVersionFileHeader.Extra[]byteFileHeader.Flagsuint16 Method is the compression method. If zero, Store is used. 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. ModifiedDate is an MS-DOS-encoded date.
Deprecated: Use Modified instead. ModifiedTime is an MS-DOS-encoded time.
Deprecated: Use Modified instead. 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. 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.FileHeader.ReaderVersionuint16 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. UncompressedSize64 is the uncompressed size of the file in bytes. DataOffset returns the offset of the file's possibly-compressed
data, relative to the beginning of the zip file.
Most callers should instead use [File.Open], which transparently
decompresses data and verifies checksums. FileInfo returns an fs.FileInfo for the [FileHeader]. ModTime returns the modification time in UTC using the legacy
[ModifiedDate] and [ModifiedTime] fields.
Deprecated: Use [Modified] instead. Mode returns the permission and mode bits for the [FileHeader]. Open returns a [ReadCloser] that provides access to the [File]'s contents.
Multiple files may be read concurrently. OpenRaw returns a [Reader] that provides access to the [File]'s contents without
decompression. SetModTime sets the [Modified], [ModifiedTime], and [ModifiedDate] fields
to the given time in UTC.
Deprecated: Use [Modified] instead. SetMode changes the permission and mode bits for the [FileHeader].
func (*Writer).Copy(f *File) error
FileHeader describes a file within a ZIP file.
See the [ZIP specification] for details. CRC32 is the CRC32 checksum of the file content.
Comment is any arbitrary user-defined string shorter than 64KiB.
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. CompressedSize64 is the compressed size of the file in bytes.CreatorVersionuint16 // Meaning depends on CreatorVersionExtra[]byteFlagsuint16 Method is the compression method. If zero, Store is used. 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. ModifiedDate is an MS-DOS-encoded date.
Deprecated: Use Modified instead. ModifiedTime is an MS-DOS-encoded time.
Deprecated: Use Modified instead. 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. 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.ReaderVersionuint16 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. UncompressedSize64 is the uncompressed size of the file in bytes. FileInfo returns an fs.FileInfo for the [FileHeader]. ModTime returns the modification time in UTC using the legacy
[ModifiedDate] and [ModifiedTime] fields.
Deprecated: Use [Modified] instead. Mode returns the permission and mode bits for the [FileHeader]. SetModTime sets the [Modified], [ModifiedTime], and [ModifiedDate] fields
to the given time in UTC.
Deprecated: Use [Modified] instead. SetMode changes the permission and mode bits for the [FileHeader].
func FileInfoHeader(fi fs.FileInfo) (*FileHeader, error)
func (*Writer).CreateHeader(fh *FileHeader) (io.Writer, error)
func (*Writer).CreateRaw(fh *FileHeader) (io.Writer, error)
A ReadCloser is a [Reader] that must be closed when no longer needed.ReaderReaderReader.CommentstringReader.File[]*File Close closes the Zip file, rendering it unusable for I/O. Open opens the named file in the ZIP archive,
using the semantics of fs.FS.Open:
paths are always slash separated, with no
leading / or ../ elements. RegisterDecompressor registers or overrides a custom decompressor for a
specific method ID. If a decompressor for a given method is not found,
[Reader] will default to looking up the decompressor at the package level.
*ReadCloser : io.Closer
*ReadCloser : io/fs.FS
func OpenReader(name string) (*ReadCloser, error)
A Reader serves content from a ZIP archive.CommentstringFile[]*File Open opens the named file in the ZIP archive,
using the semantics of fs.FS.Open:
paths are always slash separated, with no
leading / or ../ elements. RegisterDecompressor registers or overrides a custom decompressor for a
specific method ID. If a decompressor for a given method is not found,
[Reader] will default to looking up the decompressor at the package level.
*Reader : io/fs.FS
func NewReader(r io.ReaderAt, size int64) (*Reader, error)
Writer implements a zip file writer. AddFS adds the files from fs.FS to the archive.
It walks the directory tree starting at the root of the filesystem
adding each file to the zip using deflate while maintaining the directory structure. Close finishes writing the zip file by writing the central directory.
It does not close the underlying writer. Copy copies the file f (obtained from a [Reader]) into w. It copies the raw
form directly bypassing decompression, compression, and validation. Create adds a file to the zip file using the provided name.
It returns a [Writer] to which the file contents should be written.
The file contents will be compressed using the [Deflate] method.
The name must be a relative path: it must not start with a drive
letter (e.g. C:) or leading slash, and only forward slashes are
allowed. To create a directory instead of a file, add a trailing
slash to the name.
The file's contents must be written to the [io.Writer] before the next
call to [Writer.Create], [Writer.CreateHeader], or [Writer.Close]. CreateHeader adds a file to the zip archive using the provided [FileHeader]
for the file metadata. [Writer] takes ownership of fh and may mutate
its fields. The caller must not modify fh after calling [Writer.CreateHeader].
This returns a [Writer] to which the file contents should be written.
The file's contents must be written to the io.Writer before the next
call to [Writer.Create], [Writer.CreateHeader], [Writer.CreateRaw], or [Writer.Close]. CreateRaw adds a file to the zip archive using the provided [FileHeader] and
returns a [Writer] to which the file contents should be written. The file's
contents must be written to the io.Writer before the next call to [Writer.Create],
[Writer.CreateHeader], [Writer.CreateRaw], or [Writer.Close].
In contrast to [Writer.CreateHeader], the bytes passed to Writer are not compressed.
CreateRaw's argument is stored in w. If the argument is a pointer to the embedded
[FileHeader] in a [File] obtained from a [Reader] created from in-memory data,
then w will refer to all of that memory. Flush flushes any buffered data to the underlying writer.
Calling Flush is not normally necessary; calling Close is sufficient. RegisterCompressor registers or overrides a custom compressor for a specific
method ID. If a compressor for a given method is not found, [Writer] will
default to looking up the compressor at the package level. SetComment sets the end-of-central-directory comment field.
It can only be called before [Writer.Close]. SetOffset sets the offset of the beginning of the zip data within the
underlying writer. It should be used when the zip data is appended to an
existing file, such as a binary executable.
It must be called before any data is written.
*Writer : io.Closer
func NewWriter(w io.Writer) *Writer
Package-Level Functions (total 6)
FileInfoHeader creates a partially-populated [FileHeader] from an
fs.FileInfo.
Because fs.FileInfo's Name method returns only the base name of
the file it describes, it may be necessary to modify the Name field
of the returned header to provide the full path name of the file.
If compression is desired, callers should set the FileHeader.Method
field; it is unset by default.
NewReader returns a new [Reader] reading from r, which is assumed to
have the given size in bytes.
If any file inside the archive uses a non-local name
(as defined by [filepath.IsLocal]) or a name containing backslashes
and the GODEBUG environment variable contains `zipinsecurepath=0`,
NewReader 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 ignore
the [ErrInsecurePath] error and use the returned reader.
NewWriter returns a new [Writer] writing a zip file to w.
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 by [filepath.IsLocal]) or a name containing backslashes
and 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 ignore
the ErrInsecurePath error and use the returned reader.
RegisterCompressor registers custom compressors for a specified method ID.
The common methods [Store] and [Deflate] are built in.
RegisterDecompressor allows custom decompressors for a specified method ID.
The common methods [Store] and [Deflate] are built in.
The pages are generated with Goldsv0.7.0-preview. (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu.
PR and bug reports are welcome and can be submitted to the issue list.
Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds.