Compress Streams With compress/flate

Compress and restore data with compress/flate writers and readers, comparing compressed sizes and verifying a byte-exact round trip.

GoData Integrity

Code

gosnippet
42 lines
package main

import (
	"bytes"
	"compress/flate"
	"fmt"
	"io"
)

func main() {
	original := bytes.Repeat([]byte("deflate-me "), 32)

	var compressed bytes.Buffer
	// BestCompression 换成 flate.BestSpeed 可降低 CPU 开销
	w, err := flate.NewWriter(&compressed, flate.BestCompression)
	if err != nil {
		fmt.Println("writer failed:", err)
		return
	}
	if _, err := w.Write(original); err != nil {
		fmt.Println("write failed:", err)
		return
	}
	// Close 才会写出剩余块并刷新尾部
	if err := w.Close(); err != nil {
		fmt.Println("close failed:", err)
		return
	}
	fmt.Println("original bytes:", len(original))
	fmt.Println("compressed bytes:", compressed.Len())

	// flate 是裸 deflate 流:没有 zlib/gzip 头
	r := flate.NewReader(bytes.NewReader(compressed.Bytes()))
	decompressed, err := io.ReadAll(r)
	if err != nil {
		fmt.Println("read failed:", err)
		return
	}
	r.Close()
	fmt.Println("restored bytes:", len(decompressed))
	fmt.Println("roundtrip equal:", bytes.Equal(original, decompressed))
}

How the snippet works

Compress Streams With compress/flate comes down to the function main.

err is inspected at 4 call sites before any result is trusted.

Applying it

The run emits 8 labeled sections — writer failed:, write failed:, close failed:, original bytes:, compressed bytes:, read failed:, restored bytes:, roundtrip equal: — one per step.

Statements that carry the weight

if err != nil {
	fmt.Println("writer failed:", err)
	return
}
if err != nil {
	fmt.Println("read failed:", err)
	return
}

Interactive Tools for This Topic

FAQ

What does Compress Streams With compress/flate print when run?
Run it as a complete program — the output lines carry labels such as `writer failed:`, `write failed:`, `close failed:`.