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.

GoSecurity Boundaries

Code

snippet
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 err before 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

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=`.