Compress and archive controlled data
Compress and archive controlled data
Compression reduces repeated information; an archive groups named entries. gzip wraps a stream, whereas ZIP stores named files and metadata. Start with a short string in memory. A compressed input can expand dramatically, so set a maximum decoded size before reading it.
package main
import ( "bytes" "compress/gzip" "errors" "fmt" "io")
func compress(s string) []byte { var b bytes.Buffer w := gzip.NewWriter(&b) if _, e := w.Write([]byte(s)); e != nil { panic(e) } if e := w.Close(); e != nil { panic(e) } return b.Bytes()}func unpack(data []byte, limit int64) (string, error) { r, e := gzip.NewReader(bytes.NewReader(data)) if e != nil { return "", e } defer r.Close() b, e := io.ReadAll(io.LimitReader(r, limit+1)) if e != nil { return "", e } if int64(len(b)) > limit { return "", errors.New("too large") } return string(b), nil}func main() { s, e := unpack(compress("hello"), 5) fmt.Println(s, e == nil) _, e = unpack(compress("hello"), 4) fmt.Println(e != nil)}Close finishes the gzip stream and writes its trailer. The reader must reach EOF successfully to verify the checksum; Close alone does not verify it. Reading at most limit+1 bytes distinguishes exact size from overflow. Here the limit is a small trusted positive constant; validate configurable limits to avoid integer overflow. CRC checks accidental corruption, not authenticity.
Expected output:
hello truetrueZIP entries without extraction
package main
import ( "archive/zip" "bytes" "fmt" "io")
func archive() []byte { var b bytes.Buffer w := zip.NewWriter(&b) f, e := w.Create("note.txt") if e != nil { panic(e) } if _, e = f.Write([]byte("hello")); e != nil { panic(e) } if e = w.Close(); e != nil { panic(e) } return b.Bytes()}func main() { b := archive() r, e := zip.NewReader(bytes.NewReader(b), int64(len(b))) if e != nil { panic(e) } f := r.File[0] rc, e := f.Open() if e != nil { panic(e) } v, e := io.ReadAll(io.LimitReader(rc, 6)) ce := rc.Close() if e != nil || ce != nil || len(v) > 5 { panic("invalid entry") } fmt.Println(f.Name, string(v))}ZIP needs random access and the archive length. This example reads a known entry without creating files. For untrusted archives cap compressed bytes, entries and total decoded bytes; reject unsafe paths and symlinks before extraction. A simple string prefix check is not sufficient for filesystem containment. Do not extract arbitrary archives in this lab.
Expected output:
note.txt helloTry it locally
Compress an empty string and a six-byte string. Verify acceptance at limit 5 for empty data and rejection for six bytes.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Specialized library 01: Compress and archive controlled data
Check the lesson objective before moving on.
Why read limit+1 bytes?
What does gzip Reader.Close alone prove?