go
50 lines · 7 steps
Computing SHA-256 checksums in Go
Streaming file hashing that scales up to whole directory trees keyed by relative path.
Explained by
highlit
1package checksum
2
3import (
4 "crypto/sha256"
5 "encoding/hex"
6 "fmt"
7 "io"
8 "os"
9 "path/filepath"
10)
11
12func File(path string) (string, error) {
13 f, err := os.Open(path)
14 if err != nil {
15 return "", err
16 }
17 defer f.Close()
18
19 h := sha256.New()
20 if _, err := io.Copy(h, f); err != nil {
21 return "", fmt.Errorf("hashing %s: %w", path, err)
22 }
23 return hex.EncodeToString(h.Sum(nil)), nil
24}
25
26func Dir(root string) (map[string]string, error) {
27 sums := make(map[string]string)
28 err := filepath.WalkDir(root, func(path string, d os.DirEntry, err error) error {
29 if err != nil {
30 return err
31 }
32 if d.IsDir() {
33 return nil
34 }
35 sum, err := File(path)
36 if err != nil {
37 return err
38 }
39 rel, err := filepath.Rel(root, path)
40 if err != nil {
41 return err
42 }
43 sums[rel] = sum
44 return nil
45 })
46 if err != nil {
47 return nil, err
48 }
49 return sums, nil
50}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Streaming a file through io.Copy into a hash keeps memory flat regardless of file size.
- 2defer Close ties resource cleanup to the function scope so every return path is covered.
- 3WalkDir with a closure lets you accumulate per-file results into a shared map cleanly.
Related explainers
go
package theme import ( "fmt"
Per-tenant HTML templates with Gin's renderer
multi-tenancy
concurrency
html-templates
Advanced
8 steps
go
package auth import ( "net/http"
Setting and reading secure session cookies in Go
cookies
session-management
security
Intermediate
6 steps
go
package middleware import ( "net/http"
A maintenance-mode gate in Gin
middleware
atomic-flag
concurrency
Intermediate
8 steps
go
func ServeVideo(c *gin.Context) { id := c.Param("id") video, err := videoRepo.FindByID(c.Request.Context(), id) if err != nil {
Streaming video files with Gin
http streaming
range requests
file serving
Intermediate
6 steps
go
package handler type LineItem struct { SKU string `json:"sku" binding:"required,alphanum"`
Structured validation errors in Gin
validation
json-binding
error-handling
Intermediate
8 steps
go
package deepcopy import ( "bytes"
Deep copying any value with gob in Go
deep-copy
serialization
generics
Intermediate
6 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/computing-sha-256-checksums-in-go-explained-go-e244/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.