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.
Code
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
SHA-256 Hash GeneratorGenerate SHA-256 cryptographic hashes from text input using the Web Crypto API. Compare hashes and verify data integrity with hexadecimal digest output.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.Webhook HMAC Signature VerifierVerify and generate HMAC-SHA256 webhook signatures for Stripe, GitHub, and raw hex headers locally using Web Crypto and constant-time comparison.Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.