TeeReader Feeds A Hasher While Copying

io.TeeReader mirrors every byte read into a hash.Hash, so one io.Copy pass forwards the payload and produces its digest without buffering it twice.

GoData Integrity

Code

gosnippet
27 lines
package main

import (
	"bytes"
	"crypto/sha256"
	"fmt"
	"io"
)

func main() {
	payload := []byte("upload line one\nupload line two\n")
	hasher := sha256.New()
	var sink bytes.Buffer

	// TeeReader mirrors every read byte into the hasher: forwarding and hashing in one pass
	source := io.TeeReader(bytes.NewReader(payload), hasher)
	n, err := io.Copy(&sink, source)
	if err != nil {
		panic(err)
	}
	fmt.Println("copied:", n, "sink size:", sink.Len())
	fmt.Printf("digest: %x\n", hasher.Sum(nil))

	// Matches hashing the raw data directly: not a single byte missed
	direct := sha256.Sum256(payload)
	fmt.Println("matches direct hash:", bytes.Equal(hasher.Sum(nil), direct[:]))
}

How it works

TeeReader Feeds A Hasher While Copying keeps everything in the function main.

Every err != nil branch (1 site) calls panic(err) — the run stops at the first failure instead of continuing in a broken state.

Watch out for

  • Failures abort via panic(err) — nothing is returned for the caller to check, and nothing in the snippet recovers.

Putting it to use

Running the file prints labeled results such as copied:, digest:, matches direct hash: — each operation’s effect is visible in the output.

The core lines of the flow

if err != nil {
panic(err)
}

Interactive Tools for This Topic

FAQ

What happens when a call fails?
There are no error returns here: a non-nil `err` reaches `panic(err)` immediately.
What does TeeReader Feeds A Hasher While Copying print when run?
The script runs standalone; its 3 labeled outputs include `copied:`, `digest:`, `matches direct hash:`.