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.
Code
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
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.bcrypt Cost EstimatorEstimate bcrypt cost factor latency and brute-force resistance, and get a recommended cost for your target hash time and attacker throughput.Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.