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.

GoData Integrity

Code

gosnippet
39 lines
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

FAQ

What does Zlib Roundtrip With Adler-32 Checksums print when run?
The script runs standalone; its 7 labeled outputs include `compress:`, `close:`, `original:`.