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.
Code
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
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.