实现说明
TeeReader 边拷贝边喂哈希以函数 main为骨架。
err 在 1 处被测试,非 nil 就以 panic(err) 中止运行。
使用要点
- 示例不返回错误——任何非 nil 的
err都会让运行立即结束。 - 每一步打印都带着自己的标签:
copied:、digest:、matches direct hash:。
常见问题
调用失败时会发生什么?
这里没有错误返回值:非 nil 的 err 会立即走到 panic(err)。
运行「TeeReader 边拷贝边喂哈希」会打印什么?
文件本身就是完整程序,直接运行——输出行带有 copied:、digest:、matches direct hash: 这类标签。
核心语句
if err != nil {
panic(err)
}
代码示例
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[:]))
}