Gzip Compress And Decompress In Memory

gzip.Writer wraps a byte buffer and Close flushes the final block; gzip.Reader hands the stream back through io.Copy so the round trip restores bytes exactly.

GoData Integrity

Code

gosnippet
40 lines
package main

import (
	"bytes"
	"compress/gzip"
	"fmt"
	"io"
	"strings"
)

func main() {
	payload := strings.Repeat("event log line with repeated content\n", 20)

	// 压缩:gzip.Writer 包装字节缓冲,Close 写出 gzip 尾块并冲出剩余数据
	var compressed bytes.Buffer
	gz := gzip.NewWriter(&compressed)
	if _, err := gz.Write([]byte(payload)); err != nil {
		panic(err)
	}
	if err := gz.Close(); err != nil {
		panic(err)
	}
	fmt.Println("original:", len(payload), "compressed:", compressed.Len())

	// 解压:gzip.Reader 交给 io.Copy 逐块还原
	gzr, err := gzip.NewReader(bytes.NewReader(compressed.Bytes()))
	if err != nil {
		panic(err)
	}
	var restored bytes.Buffer
	if _, err := io.Copy(&restored, gzr); err != nil {
		panic(err)
	}
	if err := gzr.Close(); err != nil {
		panic(err)
	}

	// 往返校验:解压结果与原文逐字节一致
	fmt.Println("restored matches:", restored.String() == payload)
}

What the code does

Gzip Compress And Decompress In Memory is built around the function main.

Nothing continues past an unchecked error — 5 if err != nil branches, each ending in panic(err).

What to watch for

  • Adapting this to library code usually means replacing the panic(err) calls with error returns the caller can branch on.

Applying it

Running the file prints labeled results such as original:, restored matches: — each operation’s effect is visible in the output.

Statements that carry the weight

if err != nil {
panic(err)
}

Interactive Tools for This Topic

FAQ

How are errors reported?
By aborting: each of the 5 `err != nil` branches calls `panic(err)`, so a failure stops the program at the point it is detected.
What does Gzip Compress And Decompress In Memory print when run?
Execute the whole file; each printed line is prefixed with a label like `original:`, `restored matches:`.