SHA-256 File Checksum Streamed With io.Copy
Compute file digests by streaming bytes through sha256.New with io.Copy, and confirm the small-payload path with sha256.Sum256 on the same content.
Code
package main
import (
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"os"
"path/filepath"
)
// checksumFile 流式读取文件计算 SHA-256,不把整个文件载入内存
func checksumFile(path string) (string, error) {
file, err := os.Open(path)
if err != nil {
return "", err
}
defer file.Close()
hasher := sha256.New()
if _, err := io.Copy(hasher, file); err != nil {
return "", err
}
return hex.EncodeToString(hasher.Sum(nil)), nil
}
func main() {
path := filepath.Join(os.TempDir(), "devexamples-sha256.txt")
payload := []byte("release notes v1
checksum line
")
if err := os.WriteFile(path, payload, 0o600); err != nil {
panic(err)
}
defer os.Remove(path)
sum, err := checksumFile(path)
if err != nil {
panic(err)
}
fmt.Println("streamed:", sum)
// 小数据可以一步到位:Sum256 直接返回摘要数组
fmt.Println("sum256: ", hex.EncodeToString(sha256.Sum256(payload)[:]))
// 内容改动一个字节,摘要必然不同
payload[0] = 'R'
fmt.Println("mutated:", hex.EncodeToString(sha256.Sum256(payload)[:]))
}Behavior at a glance
Count the functions checksumFile and main as the entire surface area of SHA-256 File Checksum Streamed With io.Copy.
Every fallible call checks err != nil (4 sites), so an error is handled where it happens rather than bubbling invisibly. Cleanup is attached with defer, so it runs on every exit path of the function.
What to watch for
erroris part of the return tuple, so every caller decides what failure means.
Putting it to use
Signature: func checksumFile(path string) (string, error)
Running the file prints labeled results such as streamed:, sum256:, mutated: — each operation’s effect is visible in the output.
The entry point wires checksumFile together — run it once and the whole demo flows.
Core lines
func checksumFile(path string) (string, error) {
file, err := os.Open(path)
if err != nil {
return "", err
}
defer file.Close()
hasher := sha256.New()
if _, err := io.Copy(hasher, file); err != nil {
return "", err
}
return hex.EncodeToString(hasher.Sum(nil)), nil
}
if err != nil {
panic(err)
}
defer os.Remove(path)
Interactive Tools for This Topic
FAQ
- How does the code signal failure?
- As returned `error` values — 4 sites in the snippet check `err` before using other results.
- What does SHA-256 File Checksum Streamed With io.Copy print when run?
- The script runs standalone; its 3 labeled outputs include `streamed:`, `sum256:`, `mutated:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.