FS Sub Mounts Subtree Root
Mount one directory of an fs.FS as its own root with fs.Sub, read files through the narrowed view, and confirm parent paths are refused.
Code
package main
import (
"fmt"
"io/fs"
"testing/fstest"
)
func main() {
files := fstest.MapFS{
"config/app.yaml": &fstest.MapFile{Data: []byte("name: demo\n")},
"config/ports.txt": &fstest.MapFile{Data: []byte("8080\n")},
"README.md": &fstest.MapFile{Data: []byte("# demo\n")},
}
// fs.Sub exposes config as the subtree root of the view
sub, err := fs.Sub(files, "config")
if err != nil {
fmt.Println("sub failed:", err)
return
}
data, err := fs.ReadFile(sub, "app.yaml")
if err != nil {
fmt.Println("read failed:", err)
return
}
fmt.Print("app.yaml: ", string(data))
entries, err := fs.ReadDir(sub, ".")
if err != nil {
fmt.Println("read dir failed:", err)
return
}
for _, entry := range entries {
fmt.Println("entry:", entry.Name())
}
_, err = fs.ReadFile(sub, "../README.md")
fmt.Println("escape blocked:", err != nil)
}The code, statement by statement
FS Sub Mounts Subtree Root comes down to the function main.
A single loop drives the file — for _, entry := range entries. Error handling is inline: 3 places test err != nil and branch immediately.
What to watch for
- No external packages — everything relies on the language’s built-in APIs.
Using it
Signature: func main()
Running the file prints labeled results such as sub failed:, read failed:, app.yaml: — each operation’s effect is visible in the output.
Key statements
for _, entry := range entries {
fmt.Println("entry:", entry.Name())
}
if err != nil {
fmt.Println("sub failed:", err)
return
}
if err != nil {
fmt.Println("read failed:", err)
return
}
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
- What does FS Sub Mounts Subtree Root print when run?
- The script runs standalone; its 6 labeled outputs include `sub failed:`, `read failed:`, `app.yaml:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.