fs ValidPath Validates FS Paths
Validate path shape with fs.ValidPath before any fs.FS read, rejecting absolute paths, dot segments, and empty elements at the gate.
Code
package main
import (
"fmt"
"io/fs"
"os"
)
func readUnder(root fs.FS, name string) (string, error) {
// fs.FS 只接受 ValidPath 形状:非绝对、不含 . 与 ..、无空段
if !fs.ValidPath(name) {
return "", fmt.Errorf("invalid fs path: %q", name)
}
return fs.ReadFile(root, name)
}
func main() {
root := os.DirFS(".")
for _, name := range []string{"go.mod", "/etc/passwd", "../secrets.txt"} {
data, err := readUnder(root, name)
if err != nil {
fmt.Println(name, "-> rejected:", err)
continue
}
fmt.Println(name, "->", len(data), "bytes")
}
}How this snippet works
All of the logic lives in the functions readUnder and main.
Iteration happens inside for _, name := range []string{"go.mod", "/etc/passwd", "../secrets.txt"} — everything outside it runs once. Every fallible call checks err != nil (1 site), so an error is handled where it happens rather than bubbling invisibly.
Caveats
- No installation is involved: the snippet works within the standard library.
- Error values are returned, not thrown — every call site must inspect
errbefore using the other return values.
Applying it
The main signature reads func readUnder(root fs.FS, name string) (string, error)
Running the file executes main, which drives readUnder in order.
Statements that matter
return "", fmt.Errorf("invalid fs path: %q", name)
for _, name := range []string{"go.mod", "/etc/passwd", "../secrets.txt"} {
data, err := readUnder(root, name)
if err != nil {
fmt.Println(name, "-> rejected:", err)
continue
}
fmt.Println(name, "->", len(data), "bytes")
}
return fs.ReadFile(root, name)
Interactive Tools for This Topic
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.
FAQ
- How are errors reported?
- The Go way: `err` comes back from each call, and 1 checkpoint here test it before proceeding.
- How do you run fs ValidPath Validates FS Paths?
- It runs as-is — treat the file as the whole program and execute it.
Report a problem with this exampleOpens a pre-filled issue on GitHub.