Overview

Package zip provides support for reading and writing ZIP archives.

See: https://www.pkware.com/appnote

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.

Index

Package files

register.go writer.go

Constants

Compression methods.

  1. var (
  2. ErrFormat = .New("zip: not a valid zip file")
  3. ErrAlgorithm = .New("zip: unsupported compression algorithm")
  4. ErrChecksum = .New("zip: checksum error")
  5. )

func

  1. func RegisterCompressor(method , comp Compressor)

RegisterCompressor registers custom compressors for a specified method ID. The
common methods Store and Deflate are built in.

func

  1. func RegisterDecompressor(method , dcomp Decompressor)

RegisterDecompressor allows custom decompressors for a specified method ID. The
common methods Store and Deflate are built in.

type

  1. type Compressor func(w .Writer) (.WriteCloser, )

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.

  1. type Decompressor func(r io.) io.

A Decompressor returns a new decompressing reader, reading from r. The
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.

type File

  1. type File struct {
  2. FileHeader
  3. // contains filtered or unexported fields
  4. }

func (*File)

  1. func (f *) DataOffset() (offset int64, err )

DataOffset returns the offset of the file’s possibly-compressed data, relative
to the beginning of the zip file.

Most callers should instead use Open, which transparently decompresses data and
verifies checksums.

func (*File) Open

  1. func (f *File) Open() (.ReadCloser, )

Open returns a ReadCloser that provides access to the File’s contents. Multiple
files may be read concurrently.

type FileHeader

  1. type FileHeader struct {
  2. // Name is the name of the file.
  3. // It must be a relative path, not start with a drive letter (e.g. C:),
  4. // and must use forward slashes instead of back slashes.
  5. Name string
  6.  
  7. // Comment is any arbitrary user-defined string shorter than 64KiB.
  8. Comment
  9.  
  10. // NonUTF8 indicates that Name and Comment are not encoded in UTF-8.
  11. //
  12. // By specification, the only other encoding permitted should be CP-437,
  13. // the system's local character encoding happens to be.
  14. //
  15. // This flag should only be set if the user intends to encode a non-portable
  16. // ZIP file for a specific localized region. Otherwise, the Writer
  17. // automatically sets the ZIP format's UTF-8 flag for valid UTF-8 strings.
  18. NonUTF8 bool
  19.  
  20. CreatorVersion
  21. ReaderVersion uint16
  22. Flags
  23.  
  24. // Method is the compression method. If zero, Store is used.
  25. Method uint16
  26.  
  27. // Modified is the modified time of the file.
  28. //
  29. // When reading, an extended timestamp is preferred over the legacy MS-DOS
  30. // date field, and the offset between the times is used as the timezone.
  31. // If only the MS-DOS date is present, the timezone is assumed to be UTC.
  32. //
  33. // When writing, an extended timestamp (which is timezone-agnostic) is
  34. // always emitted. The legacy MS-DOS date field is encoded according to the
  35. // location of the Modified time.
  36. Modified .Time
  37. ModifiedTime // Deprecated: Legacy MS-DOS date; use Modified instead.
  38. ModifiedDate uint16 // Deprecated: Legacy MS-DOS time; use Modified instead.
  39.  
  40. CRC32
  41. CompressedSize uint32 // Deprecated: Use CompressedSize64 instead.
  42. UncompressedSize // Deprecated: Use UncompressedSize64 instead.
  43. CompressedSize64 uint64
  44. UncompressedSize64
  45. Extra []byte
  46. ExternalAttrs // Meaning depends on CreatorVersion
  47. }

FileHeader describes a file within a zip file. See the zip spec for details.

func FileInfoHeader

  1. func FileInfoHeader(fi os.) (*FileHeader, )

FileInfoHeader creates a partially-populated FileHeader from an os.FileInfo.
Because os.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.

func (*FileHeader) FileInfo

FileInfo returns an os.FileInfo for the FileHeader.

func (*FileHeader) ModTime

  1. func (h *FileHeader) ModTime() .Time

ModTime returns the modification time in UTC using the legacy ModifiedDate and
ModifiedTime fields.

Deprecated: Use Modified instead.

  1. func (h *) Mode() (mode os.)

Mode returns the permission and mode bits for the FileHeader.

func (*FileHeader) SetModTime

  1. func (h *FileHeader) SetModTime(t .Time)

SetModTime sets the Modified, ModifiedTime, and ModifiedDate fields to the given
time in UTC.

Deprecated: Use Modified instead.

func (*FileHeader)

  1. func (h *) SetMode(mode os.)

SetMode changes the permission and mode bits for the FileHeader.

type ReadCloser

  1. type ReadCloser struct {
  2. Reader
  3. // contains filtered or unexported fields
  4. }

func

  1. func OpenReader(name ) (*ReadCloser, )

OpenReader will open the Zip file specified by name and return a ReadCloser.

func (*ReadCloser) Close

  1. func (rc *ReadCloser) Close()

Close closes the Zip file, rendering it unusable for I/O.

  1. type Reader struct {
  2. File []*File
  3. Comment
  4. // contains filtered or unexported fields
  5. }


Example:

  1. // Open a zip archive for reading.
  2. r, err := zip.OpenReader("testdata/readme.zip")
  3. if err != nil {
  4. log.Fatal(err)
  5. }
  6. defer r.Close()
  7. // Iterate through the files in the archive,
  8. // printing some of their contents.
  9. for _, f := range r.File {
  10. fmt.Printf("Contents of %s:\n", f.Name)
  11. rc, err := f.Open()
  12. if err != nil {
  13. log.Fatal(err)
  14. _, err = io.CopyN(os.Stdout, rc, 68)
  15. if err != nil {
  16. log.Fatal(err)
  17. }
  18. rc.Close()
  19. fmt.Println()
  20. }
  21. // Contents of README:
  22. // This is the source code repository for the Go programming language.

func

  1. func NewReader(r .ReaderAt, size ) (*Reader, )

func (*Reader) RegisterDecompressor

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.

type Writer

  1. type Writer struct {
  2. // contains filtered or unexported fields
  3. }

Writer implements a zip file writer.


Example:

  1. // Create a buffer to write our archive to.
  2. buf := new(bytes.Buffer)
  3. // Create a new zip archive.
  4. w := zip.NewWriter(buf)
  5. // Add some files to the archive.
  6. var files = []struct {
  7. Name, Body string
  8. }{
  9. {"readme.txt", "This archive contains some text files."},
  10. {"gopher.txt", "Gopher names:\nGeorge\nGeoffrey\nGonzo"},
  11. {"todo.txt", "Get animal handling licence.\nWrite more examples."},
  12. }
  13. for _, file := range files {
  14. f, err := w.Create(file.Name)
  15. if err != nil {
  16. log.Fatal(err)
  17. }
  18. _, err = f.Write([]byte(file.Body))
  19. log.Fatal(err)
  20. }
  21. }
  22. // Make sure to check the error on Close.
  23. err := w.Close()
  24. if err != nil {
  25. log.Fatal(err)
  26. }

  1. func NewWriter(w .Writer) *

NewWriter returns a new Writer writing a zip file to w.

func (*Writer) Close

  1. func (w *Writer) Close()

Close finishes writing the zip file by writing the central directory. It does
not (and cannot) close the underlying writer.

func (*Writer) Create

  1. func (w *Writer) Create(name ) (io., error)

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. The file’s contents must be written to the io.Writer before
the next call to Create, CreateHeader, or Close.

func (*Writer)

  1. func (w *) CreateHeader(fh *FileHeader) (.Writer, )

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 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 Create,
CreateHeader, or Close.

func (*Writer) Flush

  1. func (w *Writer) Flush()

Flush flushes any buffered data to the underlying writer. Calling Flush is not
normally necessary; calling Close is sufficient.

func (*Writer) RegisterCompressor

  1. func (w *Writer) RegisterCompressor(method , comp Compressor)

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.


Example:

  1. // Override the default Deflate compressor with a higher compression level.
  2. // Create a buffer to write our archive to.
  3. buf := new(bytes.Buffer)
  4. // Create a new zip archive.
  5. w := zip.NewWriter(buf)
  6. // Register a custom Deflate compressor.
  7. w.RegisterCompressor(zip.Deflate, func(out io.Writer) (io.WriteCloser, error) {
  8. return flate.NewWriter(out, flate.BestCompression)
  9. })

func (*Writer) SetComment

  1. func (w *Writer) SetComment(comment ) error

SetComment sets the end-of-central-directory comment field. It can only be
called before Close.