Zlib Roundtrip With Adler-32 Checksums
Compress a byte stream with zlib.NewWriter, then decompress with zlib.NewReader while the underlying Adler-32 checksum validates every roundtrip.
Code
package main
import (
"bytes"
"compress/zlib"
"fmt"
"io"
)
func main() {
payload := []byte("snapshot line one\nsnapshot line two\nsnapshot line three\n")
// 压缩:zlib.Writer 包装缓冲,Close 写出校验尾块
var compressed bytes.Buffer
writer := zlib.NewWriter(&compressed)
if _, err := writer.Write(payload); err != nil {
fmt.Println("compress:", err)
return
}
if err := writer.Close(); err != nil {
fmt.Println("close:", err)
return
}
fmt.Println("original:", len(payload), "compressed:", compressed.Len())
// 解压:Reader 逐块还原,校验失败会以错误形式浮出
reader, err := zlib.NewReader(&compressed)
if err != nil {
fmt.Println("reader:", err)
return
}
restored, err := io.ReadAll(reader)
if err != nil {
fmt.Println("decompress:", err)
return
}
fmt.Println("roundtrip equal:", bytes.Equal(payload, restored))
fmt.Println("lines:", bytes.Count(restored, []byte("\n")))
}What the code does
The compressed view: all the work sits in the function main, doing all the work.
err is inspected at 4 call sites before any result is trusted.
What to watch for
- The runtime alone is required here — no packages, no install step.
Applying it
Look for the compress:, close:, original: prefixes once the file starts running; each one ties a printed line to the step that produced it.
Statements that carry the weight
if err != nil {
fmt.Println("reader:", err)
return
}
if err != nil {
fmt.Println("decompress:", 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 Zlib Roundtrip With Adler-32 Checksums print when run?
- The script runs standalone; its 7 labeled outputs include `compress:`, `close:`, `original:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.