Hash And Mirror Reads With TeeReader And MultiWriter

Wire io.TeeReader into io.MultiWriter so a single io.Copy hashes incoming bytes with SHA-256 and CRC-32 while writing two output destinations.

GoFile Upload

Code

snippet
package main

import (
	"bytes"
	"crypto/sha256"
	"fmt"
	"hash/crc32"
	"io"
	"strings"
)

func main() {
	src := strings.NewReader("manifest:v1\nartifact:build.tar\n")

	sha := sha256.New()
	crc := crc32.NewIEEE()
	var primary, replica bytes.Buffer

	// Every byte read from tee simultaneously feeds both hashers
	tee := io.TeeReader(src, io.MultiWriter(sha, crc))
	// And io.Copy writes the read bytes into two independent buffers
	written, err := io.Copy(io.MultiWriter(&primary, &replica), tee)
	if err != nil {
		fmt.Println("copy failed:", err)
		return
	}

	fmt.Printf("copied bytes: %d\n", written)
	fmt.Printf("sha256: %x\n", sha.Sum(nil))
	fmt.Printf("crc32:  %08x\n", crc.Sum32())
	fmt.Printf("mirrors match: %t\n", bytes.Equal(primary.Bytes(), replica.Bytes()))
}

Logic trace — Hash And Mirror Reads With TeeReader And MultiWriter

Execution behavior concentrates strictly inside helper main — everything else is wiring.

err is inspected at 1 call site before any result is trusted.

Watch out for

  • Dependencies remain zero because bundled runtime libraries cover every feature.

Applying it

The main entry contract opens with func main()

The run prints copy failed:, copied bytes:, sha256: — each prefix names the step that produced it.

Statements that matter

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

Interactive Tools for This Topic

FAQ

What does Hash And Mirror Reads With TeeReader And MultiWriter print when run?
Invoke the file as-is — the `copy failed:`, `copied bytes:`, `sha256:` prefixes identify which step printed each line.