Zip Reader Walks Entries And Metadata
Open an in-memory zip with zip.NewReader and read each entry via FileHeader metadata plus f.Open, so archive contents are inspected without touching disk.
Code
package main
import (
"archive/zip"
"bytes"
"fmt"
"io"
"time"
)
func main() {
// 先造一个内存归档:固定时间戳,输出可复现
var buf bytes.Buffer
w := zip.NewWriter(&buf)
stamp := time.Date(2026, 11, 18, 0, 0, 0, 0, time.UTC)
for _, name := range []string{"readme.txt", "docs/policy.txt"} {
header := &zip.FileHeader{Name: name, Method: zip.Deflate, Modified: stamp}
f, err := w.CreateHeader(header)
if err != nil {
panic(err)
}
if _, err := f.Write([]byte("content of " + name)); err != nil {
panic(err)
}
}
if err := w.Close(); err != nil {
panic(err)
}
r, err := zip.NewReader(bytes.NewReader(buf.Bytes()), int64(buf.Len()))
if err != nil {
panic(err)
}
fmt.Println("entries:", len(r.File))
for _, f := range r.File {
fmt.Printf("%-18s size=%d dir=%v modified=%s\n",
f.Name, f.UncompressedSize64, f.FileInfo().IsDir(), f.Modified.Format("2006-01-02"))
rc, err := f.Open()
if err != nil {
panic(err)
}
body, err := io.ReadAll(rc)
if err != nil {
panic(err)
}
if err := rc.Close(); err != nil {
panic(err)
}
fmt.Println(" body:", string(body))
}
}What the code does
Zip Reader Walks Entries And Metadata does all its work inside main — build the archive, then read it back.
One loop writes the two entries into the in-memory archive: for _, name := range []string{"readme.txt", "docs/policy.txt"}. All 7 panic(err) checkpoints cover archive construction and reads; with a buffer and a fresh zip.NewReader none of them fire in a normal run.
What to watch for
- The runtime is the only requirement — no packages, no install.
- Every fallible call (
CreateHeader,Write,Closeon both writer and reader,Open,ReadAll) panics instead of logging, so adapting this into a service means replacing the aborts with real handling.
Applying it
entries: 2 precedes the per-entry walk, where each file prints its name, size, dir flag, and 2026-11-18 modified date, followed by body: with the content written at build time.
Statements that matter
for _, name := range []string{"readme.txt", "docs/policy.txt"} {
header := &zip.FileHeader{Name: name, Method: zip.Deflate, Modified: stamp}
f, err := w.CreateHeader(header)
if err != nil {
panic(err)
}
if _, err := f.Write([]byte("content of " + name)); err != nil {
panic(err)
}
}
Interactive Tools for This Topic
FAQ
- How does the code signal failure?
- Through `panic(err)` — the 7 checkpoints test `err` and abort the run on the first non-nil one.
- What does Zip Reader Walks Entries And Metadata print when run?
- Running the file directly is enough — expect labeled output lines such as `entries:`, `body:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.