package zip

import "archive/zip"

zip 包提供对 ZIP 归档文件的读写支持。

详情参见 [ZIP 规范]。

本包不支持磁盘跨卷存储。

关于 ZIP64 的说明:

为保持向后兼容,FileHeader 同时包含 32 位和 64 位大小字段。 64 位字段始终存储正确数值,普通归档文件中两类字段值一致。 对于需要使用 ZIP64 格式的文件,32 位字段会设为 0xffffffff,此时必须使用 64 位字段。

Index

Examples

Constants

const (
	Store   uint16 = 0 // 无压缩
	Deflate uint16 = 8 // DEFLATE 压缩
)

压缩方法

Variables

var (
	ErrFormat       = errors.New("zip: not a valid zip file")
	ErrAlgorithm    = errors.New("zip: unsupported compression algorithm")
	ErrChecksum     = errors.New("zip: checksum error")
	ErrInsecurePath = errors.New("zip: insecure file path")
)

Functions

func RegisterCompressor

func RegisterCompressor(method uint16, comp Compressor)

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

func RegisterDecompressor

func RegisterDecompressor(method uint16, dcomp Decompressor)

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

Types

type Compressor

type Compressor func(w io.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 goroutines simultaneously, but each returned writer will be used only by one goroutine at a time.

type Decompressor

type Decompressor func(r io.Reader) io.ReadCloser

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.

type File

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 embedded FileHeader. The file content can be accessed by calling File.Open.

func (*File) DataOffset

func (f *File) DataOffset() (offset int64, err error)

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.

func (*File) Open

func (f *File) Open() (io.ReadCloser, error)

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

func (*File) OpenRaw

func (f *File) OpenRaw() (io.Reader, error)

OpenRaw returns a Reader that provides access to the File's contents without decompression.

type FileHeader

type FileHeader struct {
	// Name 为文件名称
	//
	// 必须为相对路径,不能以盘符(如 C:)开头,
	// 且必须使用正斜杠而非反斜杠。末尾带斜杠表示该条目为目录,不应包含数据
	Name string

	// Comment 为任意用户自定义字符串,长度小于 64KiB
	Comment string

	// NonUTF8 标识 Name 和 Comment 未使用 UTF-8 编码
	//
	// 按规范,唯一允许的其他编码应为 CP-437,
	// 但历史上很多 ZIP 读取器会将 Name 和 Comment 按系统本地字符编码解析
	//
	// 仅当用户需要为特定本地化区域生成非可移植 ZIP 文件时,才应设置该标志。
	// 其他情况下,Writer 会为合法 UTF-8 字符串自动设置 ZIP 格式的 UTF-8 标志
	NonUTF8 bool

	CreatorVersion uint16
	ReaderVersion  uint16
	Flags          uint16

	// Method 为压缩方法,为 0 时使用 Store(无压缩)
	Method uint16

	// Modified 为文件的修改时间
	//
	// 读取时,优先使用扩展时间戳而非旧版 MS-DOS 日期字段,
	// 时间差值会作为时区偏移。若仅存在 MS-DOS 日期,则时区默认为 UTC
	//
	// 写入时,始终生成与时区无关的扩展时间戳。
	// 旧版 MS-DOS 日期字段会按 Modified 时间的所在时区编码
	Modified time.Time

	// ModifiedTime 为 MS-DOS 编码格式的时间
	//
	// 已弃用:请改用 Modified
	ModifiedTime uint16

	// ModifiedDate 为 MS-DOS 编码格式的日期
	//
	// 已弃用:请改用 Modified
	ModifiedDate uint16

	// CRC32 为文件内容的 CRC32 校验和
	CRC32 uint32

	// CompressedSize 为文件压缩后的字节大小
	// 若文件压缩前/压缩后大小超出 32 位范围,该字段会设为 ^uint32(0)
	//
	// 已弃用:请改用 CompressedSize64
	CompressedSize uint32

	// UncompressedSize 为文件未压缩的字节大小
	// 若文件压缩前/压缩后大小超出 32 位范围,该字段会设为 ^uint32(0)
	//
	// 已弃用:请改用 UncompressedSize64
	UncompressedSize uint32

	// CompressedSize64 为文件压缩后的字节大小
	CompressedSize64 uint64

	// UncompressedSize64 为文件未压缩的字节大小
	UncompressedSize64 uint64

	Extra         []byte
	ExternalAttrs uint32 // 含义取决于 CreatorVersion
}

FileHeader 描述 ZIP 文件中的单个文件条目 详情参见 [ZIP 规范]

func FileInfoHeader

func FileInfoHeader(fi fs.FileInfo) (*FileHeader, error)

FileInfoHeader 从 fs.FileInfo 创建一个部分填充的 FileHeader 由于 fs.FileInfo 的 Name 方法仅返回文件的基础名称, 可能需要修改返回头部的 Name 字段以设置文件完整路径 若需要压缩,调用方应设置 FileHeader.Method 字段,该字段默认为空

func (*FileHeader) FileInfo

func (h *FileHeader) FileInfo() fs.FileInfo

FileInfo 返回该 FileHeader 对应的 fs.FileInfo

func (*FileHeader) ModTime

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

ModTime 通过旧版 ModifiedDate 和 ModifiedTime 字段返回 UTC 格式的修改时间

已弃用:请改用 Modified

func (*FileHeader) Mode

func (h *FileHeader) Mode() (mode fs.FileMode)

Mode 返回 FileHeader 的权限与模式位

func (*FileHeader) SetModTime

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

SetModTime 将 Modified、ModifiedTime 和 ModifiedDate 字段设置为给定的 UTC 时间

已弃用:请改用 Modified

func (*FileHeader) SetMode

func (h *FileHeader) SetMode(mode fs.FileMode)

SetMode 修改 FileHeader 的权限与模式位

type ReadCloser

type ReadCloser struct {
	Reader
	// contains filtered or unexported fields
}

A ReadCloser is a Reader that must be closed when no longer needed.

func OpenReader

func OpenReader(name string) (*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 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.

func (*ReadCloser) Close

func (rc *ReadCloser) Close() error

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

type Reader

type Reader struct {
	File    []*File
	Comment string
	// contains filtered or unexported fields
}

A Reader serves content from a ZIP archive.

Example
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()
	}
}

Output:

Contents of README:
This is the source code repository for the Go programming language.

func NewReader

func NewReader(r io.ReaderAt, size int64) (*Reader, error)

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.

func (*Reader) Open

func (r *Reader) Open(name string) (fs.File, error)

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.

func (*Reader) RegisterDecompressor

func (r *Reader) RegisterDecompressor(method uint16, dcomp Decompressor)

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

type Writer struct {
	// contains filtered or unexported fields
}

Writer implements a zip file writer.

Example
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)
	}
}

func NewWriter

func NewWriter(w io.Writer) *Writer

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

func (*Writer) AddFS

func (w *Writer) AddFS(fsys fs.FS) error

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.

func (*Writer) Close

func (w *Writer) Close() error

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

func (*Writer) Copy

func (w *Writer) Copy(f *File) error

Copy copies the file f (obtained from a Reader) into w. It copies the raw form directly bypassing decompression, compression, and validation.

func (*Writer) Create

func (w *Writer) Create(name string) (io.Writer, 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. To create a directory instead of a file, add a trailing slash to the name. Duplicate names will not overwrite previous entries and are appended to the zip file. The file's contents must be written to the io.Writer before the next call to Writer.Create, Writer.CreateHeader, or Writer.Close.

func (*Writer) CreateHeader

func (w *Writer) CreateHeader(fh *FileHeader) (io.Writer, error)

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.

func (*Writer) CreateRaw

func (w *Writer) CreateRaw(fh *FileHeader) (io.Writer, error)

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.

func (*Writer) Flush

func (w *Writer) Flush() error

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

func (*Writer) RegisterCompressor

func (w *Writer) RegisterCompressor(method uint16, 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
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.
}

func (*Writer) SetComment

func (w *Writer) SetComment(comment string) error

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

func (*Writer) SetOffset

func (w *Writer) SetOffset(n int64)

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.