ZIP Compression Implementation in Go
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓ZIP Compression runs in O(n) time and O(n) space, in Go as in every other language.
- ✓archive/zip in the standard library covers the whole container: zip.NewWriter(io.Writer) with Writer.Create(name), Writer.CreateHeader(*zip.FileHeader) and Writer.Close(), which is the call that emits the central directory.
- ✓Reviewers require the error from Writer.Close() to be checked, not merely deferred, because that call writes the central directory: a bare `defer zw.Close()` is exactly how truncated archives reach production.
- ✓The Go trap: zip.FileInfoHeader returns a header whose Method is left at zip.Store, while the convenience Writer.Create sets zip.Deflate for you.
- ✓compress/flate is pure Go with no assembly fast path, so it is typically slower than the zlib-ng-backed runtimes at the same level; flate.BestSpeed swaps in a genuinely different, cheaper encoder rather than just narrowing the match search.
What ZIP Compression actually is
ZIP Compression in Go: what you actually reach for
Go implementation
package zipper
import (
"archive/zip"
"io"
"os"
"path/filepath"
)
func WriteZip(dst string, paths []string) error {
f, err := os.Create(dst)
if err != nil {
return err
}
defer f.Close()
zw := zip.NewWriter(f)
for _, p := range paths {
fi, err := os.Stat(p)
if err != nil {
return err
}
h, err := zip.FileInfoHeader(fi)
if err != nil {
return err
}
h.Name = filepath.ToSlash(filepath.Base(p))
h.Method = zip.Deflate // FileInfoHeader leaves this at Store
w, err := zw.CreateHeader(h)
if err != nil {
return err
}
src, err := os.Open(p)
if err != nil {
return err
}
_, err = io.Copy(w, src) // w dies at the next CreateHeader
src.Close()
if err != nil {
return err
}
}
return zw.Close() // writes the central directory; check this error
}Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Go-specific trap
Performance in Go, beyond the O(n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Go type or library should I use for ZIP Compression?
archive/zip in the standard library covers the whole container: zip.NewWriter(io.Writer) with Writer.Create(name), Writer.CreateHeader(*zip.FileHeader) and Writer.Close(), which is the call that emits the central directory. Reading is zip.OpenReader(path) for a file or zip.NewReader(io.ReaderAt, size) for anything else, then File.Open(). zip.Store and zip.Deflate are the built-in methods and Writer.RegisterCompressor plugs in others. zip.Reader also satisfies fs.FS, so fs.WalkDir(zr, ".") walks an archive directly. compress/flate is the codec underneath.
What is the most common Go mistake when implementing ZIP Compression?
zip.FileInfoHeader returns a header whose Method is left at zip.Store, while the convenience Writer.Create sets zip.Deflate for you. So the moment you switch from Create to CreateHeader in order to preserve mtime and permissions, your archives silently stop compressing: no error, no warning, just files that are suddenly four times larger. You must set h.Method = zip.Deflate yourself. The second Go-only rule is that the io.Writer handed back by Create or CreateHeader is documented as valid only until the next Create, CreateHeader or Close call; stashing those writers in a slice and filling them later does not corrupt the stream: the next Create, CreateHeader or Close closes the previous fileWriter, and any later Write on it returns the error `zip: write to closed file`. The hazard is a returned error that hand-written loops routinely discard, not silent corruption.
How does ZIP Compression actually perform in Go?
compress/flate is pure Go with no assembly fast path, so it is typically slower than the zlib-ng-backed runtimes at the same level; flate.BestSpeed swaps in a genuinely different, cheaper encoder rather than just narrowing the match search. Every entry allocates a fresh flate.Writer, and its tables are inline struct fields, not a kilobyte: tokens.tokens is [65536]token (256 KiB) at every level, and levels 7-9 add advancedState's hashHead [1<<17]int32 (512 KiB) plus hashPrev [1<<15]int32 (128 KiB), on top of the 64 KiB window. Call it roughly 300 KiB per writer at the default level and about 1 MB at levels 7-9, which is why Writer.RegisterCompressor with a sync.Pool-backed constructor is the standard fix for archives with tens of thousands of small members. io.Copy into the entry writer uses a 32 KiB buffer and takes the ReadFrom path when available. Time complexity is O(n) and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialIf you are a student, see what GitHub Copilot offers students for free on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.