Walk An Isolated Subtree With fs.Sub And WalkDir
Mount a narrow directory view with fs.Sub, prune temporary folders via fs.WalkDir and fs.SkipDir, and verify parent escapes fail.
Code
package main
import (
"fmt"
"io/fs"
"testing/fstest"
)
func main() {
root := fstest.MapFS{
"secrets/key.pem": {Data: []byte("PRIVATE")},
"public/index.html": {Data: []byte("<h1>Hi</h1>")},
"public/css/theme.css": {Data: []byte("body{color:#fff}")},
"public/tmp/cache.bin": {Data: []byte("12345")},
}
pubFS, err := fs.Sub(root, "public")
if err != nil {
fmt.Println("sub failed:", err)
return
}
var total int64
err = fs.WalkDir(pubFS, ".", func(path string, d fs.DirEntry, walkErr error) error {
if walkErr != nil {
return walkErr
}
if d.IsDir() && d.Name() == "tmp" {
return fs.SkipDir
}
if !d.IsDir() {
info, err := d.Info()
if err != nil {
return err
}
total += info.Size()
fmt.Printf("served %s (%d bytes)\n", path, info.Size())
}
return nil
})
fmt.Printf("walk err=%v, total=%d bytes\n", err, total)
_, escapeErr := fs.ReadFile(pubFS, "../secrets/key.pem")
fmt.Println("parent traversal blocked:", escapeErr != nil)
}Execution breakdown — Walk An Isolated Subtree With fs.Sub And WalkDir
Walk An Isolated Subtree With fs.Sub And WalkDir is built around the function main.
Every fallible call checks err != nil (2 sites), so an error is handled where it happens rather than bubbling invisibly.
Points of care
- Package managers play zero role since every symbol belongs to core stdlib.
- Error values are returned, not thrown — every call site must inspect
errbefore using the other return values.
Putting it to use
Signature: func main()
Output lines are prefixed (sub failed:, served, walk err=), rendering each action visibly inside the printed log stream.
Core lines
if err != nil {
fmt.Println("sub failed:", err)
return
}
if err != nil {
return err
}
total += info.Size()
Interactive Tools for This Topic
Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.bcrypt Cost EstimatorEstimate bcrypt cost factor latency and brute-force resistance, and get a recommended cost for your target hash time and attacker throughput.CORS Header Policy DebuggerSimulate browser CORS preflight and credential policies against server response headers to pinpoint blocked origins, methods, or headers and fix them.CSP Header BuilderBuild a Content-Security-Policy header from per-directive sources, skipping empty ones and rejecting a blanket wildcard.
FAQ
- How are errors reported?
- As returned `error` values, checked at 2 sites — callers must branch on `err` before using the other return values. No panics or exceptions in the snippet.
- What does Walk An Isolated Subtree With fs.Sub And WalkDir print when run?
- The script runs standalone; its 4 labeled outputs include `sub failed:`, `served`, `walk err=`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.