ZIP archives

suggest change

Package archive/zip in the standard library reads and writes ZIP files. You don't need a third-party module for it.

The main types:

Creating an archive

package main

import (
	"archive/zip"
	"fmt"
	"log"
	"os"
)

func main() {
	f, err := os.Create("notes.zip")
	if err != nil {
		log.Fatal(err)
	}
	defer f.Close()

	zw := zip.NewWriter(f)

	files := []struct{ name, body string }{
		{"readme.txt", "This archive was created with archive/zip.\n"},
		{"docs/todo.txt", "- write article\n- test examples\n"},
		{"docs/done.txt", "- nothing yet\n"},
	}
	for _, file := range files {
		w, err := zw.Create(file.name)
		if err != nil {
			log.Fatal(err)
		}
		if _, err := w.Write([]byte(file.body)); err != nil {
			log.Fatal(err)
		}
	}

	// Close writes the central directory. Without it the archive is corrupt.
	if err := zw.Close(); err != nil {
		log.Fatal(err)
	}
	fmt.Println("wrote notes.zip")
}
wrote notes.zip

Things to know:

Reading an archive

zip.OpenReader opens a file and parses its central directory. r.File is a slice of entries in archive order.

package main

import (
	"archive/zip"
	"fmt"
	"io"
	"log"
)

func main() {
	r, err := zip.OpenReader("notes.zip")
	if err != nil {
		log.Fatal(err)
	}
	defer r.Close()

	for _, f := range r.File {
		fmt.Printf("%-14s %3d -> %3d bytes  %s\n",
			f.Name, f.UncompressedSize64, f.CompressedSize64, methodName(f.Method))
	}

	for _, f := range r.File {
		if f.Name != "docs/todo.txt" {
			continue
		}
		rc, err := f.Open()
		if err != nil {
			log.Fatal(err)
		}
		data, err := io.ReadAll(rc)
		rc.Close()
		if err != nil {
			log.Fatal(err)
		}
		fmt.Printf("\n%s:\n%s", f.Name, data)
	}
}

func methodName(m uint16) string {
	switch m {
	case zip.Store:
		return "stored"
	case zip.Deflate:
		return "deflated"
	}
	return fmt.Sprintf("method %d", m)
}
readme.txt      43 ->  50 bytes  deflated
docs/todo.txt   32 ->  39 bytes  deflated
docs/done.txt   14 ->  21 bytes  deflated

docs/todo.txt:
- write article
- test examples

Tiny files get bigger when deflated because of the format's fixed overhead. Compression pays off for larger, repetitive data.

f.Open() returns an io.ReadCloser that decompresses on the fly and verifies the CRC-32 checksum when you reach the end. A corrupted entry gives zip.ErrChecksum from the final Read, so read to EOF and check errors.

You can open several entries at the same time, and from several goroutines. Each f.Open() reads its own section of the file through io.ReaderAt.

Using a zip.Reader as fs.FS

*zip.Reader implements io/fs.FS. That gives you fs.ReadFile, fs.Glob, fs.WalkDir and everything else that accepts an fs.FS, such as http.FileServerFS and template.ParseFS.

package main

import (
	"archive/zip"
	"fmt"
	"io/fs"
	"log"
)

func main() {
	r, err := zip.OpenReader("notes.zip")
	if err != nil {
		log.Fatal(err)
	}
	defer r.Close()

	// *zip.ReadCloser embeds zip.Reader, which implements fs.FS.
	var fsys fs.FS = r

	data, err := fs.ReadFile(fsys, "readme.txt")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("readme.txt: %s", data)

	matches, err := fs.Glob(fsys, "docs/*.txt")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("glob:", matches)

	err = fs.WalkDir(fsys, ".", func(path string, d fs.DirEntry, err error) error {
		if err != nil {
			return err
		}
		fmt.Printf("walk: %-14s dir=%v\n", path, d.IsDir())
		return nil
	})
	if err != nil {
		log.Fatal(err)
	}
}
readme.txt: This archive was created with archive/zip.
glob: [docs/done.txt docs/todo.txt]
walk: .              dir=true
walk: docs           dir=true
walk: docs/done.txt  dir=false
walk: docs/todo.txt  dir=false
walk: readme.txt     dir=false

The docs directory is there even though the archive has no docs/ entry. The fs.FS view creates implied directories from the file paths.

Serving the contents of a zip file over HTTP takes one line: http.Handle("/", http.FileServerFS(r)).

Controlling entries with CreateHeader

CreateHeader takes a *zip.FileHeader and lets you choose the compression method, modification time, permissions and a per-file comment. This example also builds the archive in memory and reads it back with zip.NewReader.

package main

import (
	"archive/zip"
	"bytes"
	"fmt"
	"io"
	"log"
	"strings"
	"time"
)

func main() {
	var buf bytes.Buffer
	zw := zip.NewWriter(&buf)
	mod := time.Date(2026, 10, 17, 12, 0, 0, 0, time.UTC)

	// Store: no compression. Use it for data that's already compressed (JPEG, PNG, MP4).
	w, err := zw.CreateHeader(&zip.FileHeader{
		Name:     "photo.jpg",
		Method:   zip.Store,
		Modified: mod,
	})
	if err != nil {
		log.Fatal(err)
	}
	w.Write(bytes.Repeat([]byte{0xff, 0xd8}, 500))

	// Deflate, with a comment and Unix permissions.
	hdr := &zip.FileHeader{
		Name:     "bin/run.sh",
		Method:   zip.Deflate,
		Modified: mod,
		Comment:  "start script",
	}
	hdr.SetMode(0o755)
	w, err = zw.CreateHeader(hdr)
	if err != nil {
		log.Fatal(err)
	}
	io.WriteString(w, "#!/bin/sh\n"+strings.Repeat("echo hello\n", 100))

	zw.SetComment("built by example program")
	if err := zw.Close(); err != nil {
		log.Fatal(err)
	}
	fmt.Println("archive size:", buf.Len())

	// zip.NewReader needs an io.ReaderAt and the total size.
	data := buf.Bytes()
	r, err := zip.NewReader(bytes.NewReader(data), int64(len(data)))
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("archive comment:", r.Comment)
	for _, f := range r.File {
		fmt.Printf("%-10s %4d -> %4d  mode=%v  modified=%s  comment=%q\n",
			f.Name, f.UncompressedSize64, f.CompressedSize64, f.Mode(),
			f.Modified.UTC().Format(time.DateTime), f.Comment)
	}
}
archive size: 1349
archive comment: built by example program
photo.jpg  1000 -> 1000  mode=-rw-rw-rw-  modified=2026-10-17 12:00:00  comment=""
bin/run.sh 1110 ->   33  mode=-rwxr-xr-x  modified=2026-10-17 12:00:00  comment="start script"

Notes:

Zipping a directory

To archive files from disk, walk the directory and use zip.FileInfoHeader. It copies size, permissions and modification time from an fs.FileInfo.

package main

import (
	"archive/zip"
	"fmt"
	"io"
	"io/fs"
	"log"
	"os"
	"path/filepath"
	"strings"
)

// zipDir writes every file under dir into a zip archive at dst.
// Paths inside the archive are relative to dir and use forward slashes.
func zipDir(dst, dir string) error {
	out, err := os.Create(dst)
	if err != nil {
		return err
	}
	defer out.Close()

	zw := zip.NewWriter(out)
	err = filepath.WalkDir(dir, func(path string, d fs.DirEntry, err error) error {
		if err != nil {
			return err
		}
		rel, err := filepath.Rel(dir, path)
		if err != nil || rel == "." {
			return err
		}
		info, err := d.Info()
		if err != nil {
			return err
		}
		hdr, err := zip.FileInfoHeader(info) // copies size, mode, mod time
		if err != nil {
			return err
		}
		hdr.Name = filepath.ToSlash(rel)
		if d.IsDir() {
			hdr.Name += "/" // trailing slash marks a directory entry
			_, err = zw.CreateHeader(hdr)
			return err
		}
		if !info.Mode().IsRegular() {
			return nil // skip symlinks, devices, etc.
		}
		if isCompressed(path) {
			hdr.Method = zip.Store
		} else {
			hdr.Method = zip.Deflate // FileInfoHeader defaults to Store
		}
		w, err := zw.CreateHeader(hdr)
		if err != nil {
			return err
		}
		f, err := os.Open(path)
		if err != nil {
			return err
		}
		defer f.Close()
		_, err = io.Copy(w, f)
		return err
	})
	if err != nil {
		zw.Close()
		return err
	}
	if err := zw.Close(); err != nil {
		return err
	}
	return out.Close()
}

func isCompressed(path string) bool {
	switch strings.ToLower(filepath.Ext(path)) {
	case ".png", ".jpg", ".jpeg", ".gif", ".zip", ".gz", ".mp4":
		return true
	}
	return false
}

func main() {
	// site/index.html, site/css/main.css, site/img/logo.png
	if err := zipDir("site.zip", "site"); err != nil {
		log.Fatal(err)
	}
	r, err := zip.OpenReader("site.zip")
	if err != nil {
		log.Fatal(err)
	}
	defer r.Close()
	for _, f := range r.File {
		fmt.Printf("%-16s method=%d\n", f.Name, f.Method)
	}
}
css/             method=0
css/main.css     method=8
img/             method=0
img/logo.png     method=0
index.html       method=8

zip.FileInfoHeader leaves Method as Store, so the code switches to Deflate for files that compress well.

Writer.AddFS

Since Go 1.22, zw.AddFS(fsys) walks an fs.FS and adds every regular file (and, in newer versions, directory entries) for you:

out, err := os.Create("site.zip")
if err != nil {
	log.Fatal(err)
}
defer out.Close()

zw := zip.NewWriter(out)
if err := zw.AddFS(os.DirFS("site")); err != nil {
	log.Fatal(err)
}
if err := zw.Close(); err != nil {
	log.Fatal(err)
}

AddFS deflates every file and returns an error on symlinks and other non-regular files. Write the walk yourself, as in zipDir, when you need to filter files, store pre-compressed data, or skip symlinks instead of failing. AddFS also works with embed.FS and with another *zip.Reader.

Extracting safely

An archive from an untrusted source can contain names like ../../.bashrc or /etc/passwd. If you join those to the destination directory you write outside of it. This bug is called "zip slip".

A small archive can also decompress to gigabytes (a "zip bomb"). The sizes in the header are written by whoever made the archive, so you can't trust them.

package main

import (
	"archive/zip"
	"bytes"
	"errors"
	"fmt"
	"io"
	"log"
	"os"
	"path/filepath"
)

const maxFileSize = 100 << 20 // 100 MB per file

// extract unpacks the archive into dir, rejecting entries that would
// escape dir and files that decompress to more than maxFileSize.
func extract(r *zip.Reader, dir string) error {
	for _, f := range r.File {
		if !filepath.IsLocal(f.Name) {
			return fmt.Errorf("unsafe path in archive: %q", f.Name)
		}
		dst := filepath.Join(dir, f.Name)

		if f.FileInfo().IsDir() {
			if err := os.MkdirAll(dst, 0o755); err != nil {
				return err
			}
			continue
		}
		if !f.Mode().IsRegular() {
			continue // don't create symlinks from untrusted archives
		}
		if err := os.MkdirAll(filepath.Dir(dst), 0o755); err != nil {
			return err
		}
		if err := extractFile(f, dst); err != nil {
			return fmt.Errorf("%s: %w", f.Name, err)
		}
	}
	return nil
}

func extractFile(f *zip.File, dst string) error {
	rc, err := f.Open()
	if err != nil {
		return err
	}
	defer rc.Close()

	out, err := os.OpenFile(dst, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, f.Mode().Perm()|0o600)
	if err != nil {
		return err
	}
	// Limit what we actually read instead of trusting UncompressedSize64.
	n, err := io.Copy(out, io.LimitReader(rc, maxFileSize+1))
	if err == nil && n > maxFileSize {
		err = errors.New("file too large")
	}
	if cerr := out.Close(); err == nil {
		err = cerr
	}
	if err == nil {
		err = os.Chtimes(dst, f.Modified, f.Modified)
	}
	return err
}

func main() {
	r, err := zip.OpenReader("site.zip")
	if err != nil {
		log.Fatal(err)
	}
	defer r.Close()
	if err := extract(&r.Reader, "out"); err != nil {
		log.Fatal(err)
	}
	filepath.WalkDir("out", func(p string, d os.DirEntry, err error) error {
		fmt.Println(filepath.ToSlash(p))
		return nil
	})

	// Build a malicious archive in memory.
	var buf bytes.Buffer
	zw := zip.NewWriter(&buf)
	w, _ := zw.Create("../../evil.txt")
	w.Write([]byte("gotcha"))
	zw.Close()

	evil, err := zip.NewReader(bytes.NewReader(buf.Bytes()), int64(buf.Len()))
	fmt.Println("NewReader error:", err)
	fmt.Println("extract error:", extract(evil, "out"))
}
out
out/css
out/css/main.css
out/img
out/img/logo.png
out/index.html
NewReader error: <nil>
extract error: unsafe path in archive: "../../evil.txt"

filepath.IsLocal (Go 1.20+) reports whether a path stays inside the directory it's joined to. It rejects absolute paths, .. escapes, empty names and, on Windows, reserved names like NUL and volume names like C:.

By default zip.NewReader accepts insecure names for backward compatibility. Run with GODEBUG=zipinsecurepath=0 (or put godebug zipinsecurepath=0 in go.mod) to make NewReader and OpenReader return zip.ErrInsecurePath for such archives:

NewReader error: zip: insecure file path

The reader is still usable when this error is returned, so the explicit IsLocal check is still a good idea. The fs.FS view (r.Open, fs.WalkDir) cleans names instead: ../../evil.txt shows up as evil.txt.

For a total limit across the whole archive, keep a running count of extracted bytes and check the number of entries in r.File too.

Choosing the compression level

zip.Writer uses compress/flate at the default level. To change it, register your own compressor for zip.Deflate:

package main

import (
	"archive/zip"
	"bytes"
	"compress/flate"
	"fmt"
	"io"
	"log"
)

func build(level int) int {
	var buf bytes.Buffer
	zw := zip.NewWriter(&buf)
	zw.RegisterCompressor(zip.Deflate, func(out io.Writer) (io.WriteCloser, error) {
		return flate.NewWriter(out, level)
	})
	w, err := zw.Create("log.txt")
	if err != nil {
		log.Fatal(err)
	}
	for i := range 20000 {
		fmt.Fprintf(w, "%d INFO request handled path=/api/items/%d status=200\n", i, i%97)
	}
	if err := zw.Close(); err != nil {
		log.Fatal(err)
	}
	return buf.Len()
}

func main() {
	levels := []int{flate.NoCompression, flate.BestSpeed, flate.DefaultCompression, flate.BestCompression}
	for _, lvl := range levels {
		fmt.Printf("level %2d: %7d bytes\n", lvl, build(lvl))
	}
}
level  0: 1127040 bytes
level  1:   83825 bytes
level -1:   79566 bytes
level  9:   78284 bytes

BestSpeed is often the best trade-off for large archives created on the fly: much faster and only slightly bigger.

RegisterCompressor on a Writer affects only that writer. There's also a package-level zip.RegisterCompressor / zip.RegisterDecompressor for adding methods globally. Use it to read archives that use other compression methods, for example Zstandard (method 93) with github.com/klauspost/compress/zstd. Out of the box Go supports only Store and Deflate.

Modifying an existing archive

ZIP files can't be edited in place with archive/zip. To remove, replace or add entries, write a new archive.

zw.Copy(f) copies an entry from a reader without decompressing and recompressing it, so it's fast:

package main

import (
	"archive/zip"
	"fmt"
	"io"
	"log"
	"os"
)

// rewrite copies src to dst, dropping entries for which keep returns false
// and adding the extra files. Kept entries are copied without recompression.
func rewrite(dst, src string, keep func(name string) bool, extra map[string]string) error {
	r, err := zip.OpenReader(src)
	if err != nil {
		return err
	}
	defer r.Close()

	out, err := os.Create(dst)
	if err != nil {
		return err
	}
	defer out.Close()
	zw := zip.NewWriter(out)

	for _, f := range r.File {
		if !keep(f.Name) {
			continue
		}
		if err := zw.Copy(f); err != nil {
			return err
		}
	}
	for name, body := range extra {
		w, err := zw.Create(name)
		if err != nil {
			return err
		}
		if _, err := io.WriteString(w, body); err != nil {
			return err
		}
	}
	if err := zw.Close(); err != nil {
		return err
	}
	return out.Close()
}

func main() {
	err := rewrite("notes2.zip", "notes.zip",
		func(name string) bool { return name != "docs/done.txt" },
		map[string]string{"docs/ideas.txt": "- zip64\n"})
	if err != nil {
		log.Fatal(err)
	}
	r, err := zip.OpenReader("notes2.zip")
	if err != nil {
		log.Fatal(err)
	}
	defer r.Close()
	for _, f := range r.File {
		fmt.Println(f.Name)
	}
}
readme.txt
docs/todo.txt
docs/ideas.txt

To replace a file in place, write to a temporary file in the same directory and os.Rename it over the original after Close succeeds.

For lower-level control there's f.OpenRaw() (read compressed bytes) and zw.CreateRaw(hdr) (write already-compressed bytes, with sizes and CRC32 you provide).

Streaming a ZIP in an HTTP response

zip.Writer doesn't need to seek: it writes sizes and checksums after each entry's data. You can generate an archive straight into an http.ResponseWriter without building it in memory first.

package main

import (
	"archive/zip"
	"bytes"
	"fmt"
	"io"
	"log"
	"net/http"
	"net/http/httptest"
	"time"
)

type Report struct {
	Name string
	CSV  string
}

func downloadReports(w http.ResponseWriter, r *http.Request) {
	reports := []Report{
		{"sales.csv", "month,total\njan,100\nfeb,120\n"},
		{"users.csv", "id,name\n1,alice\n2,bob\n"},
	}

	w.Header().Set("Content-Type", "application/zip")
	w.Header().Set("Content-Disposition", `attachment; filename="reports.zip"`)

	zw := zip.NewWriter(w)
	for _, rep := range reports {
		fw, err := zw.CreateHeader(&zip.FileHeader{
			Name:     rep.Name,
			Method:   zip.Deflate,
			Modified: time.Now(),
		})
		if err != nil {
			log.Println(err) // headers are already sent, we can only stop
			return
		}
		if _, err := io.WriteString(fw, rep.CSV); err != nil {
			log.Println(err)
			return
		}
	}
	if err := zw.Close(); err != nil {
		log.Println(err)
	}
}

func main() {
	srv := httptest.NewServer(http.HandlerFunc(downloadReports))
	defer srv.Close()

	resp, err := http.Get(srv.URL)
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()

	// zip.Reader needs io.ReaderAt, so a response body must be buffered first.
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		log.Fatal(err)
	}
	zr, err := zip.NewReader(bytes.NewReader(body), int64(len(body)))
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(resp.Header.Get("Content-Type"))
	for _, f := range zr.File {
		fmt.Println(f.Name, f.UncompressedSize64)
	}
}
application/zip
sales.csv 28
users.csv 22

Once the first byte is written the status is 200 and you can't send an error page. If generation fails midway, the client gets a truncated archive, and archive tools report it as corrupt. If an error is likely, check everything you can before writing the first entry.

Reading is the opposite: the central directory sits at the end of the file, so zip.Reader can't read from a plain stream. Buffer small archives in memory as above, or copy large ones to a temporary file (os.CreateTemp) and use zip.OpenReader. For an HTTP server that accepts uploads, also limit the body size with http.MaxBytesReader.

Limitations and gotchas

See also: Reading files, Writing files, Directory operations and I/O related interfaces.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents