Relative Paths With filepath.Rel
Turn absolute targets into root-relative paths with filepath.Rel for reports and allowlist checks, expecting the leading .. when a target escapes the root.
Code
package main
import (
"fmt"
"path/filepath"
)
func main() {
root := "/srv/app"
for _, target := range []string{
"/srv/app/bin/tool",
"/srv/app/config/app.yaml",
"/var/log/app.log",
} {
rel, err := filepath.Rel(root, target)
if err != nil {
fmt.Println("rel:", err)
continue
}
fmt.Printf("%s -> %s\n", target, rel)
}
// 越过根的引用产生 .. 前缀;无法建立相对关系时 Rel 返回错误
joined := filepath.Join(root, "bin/tool")
back, err := filepath.Rel(root, joined)
fmt.Println("roundtrip:", back, err)
}How the pieces connect
Relative Paths With filepath.Rel is built around the function main.
Iteration happens inside for _, target := range []string — everything outside it runs once. Nothing falls through silently — 1 checkpoint test err != nil on the way through.
Points of care
- No package manager in the path — each call lands on a built-in API.
Putting it to use
Signature: func main()
The run emits 2 labeled sections — rel:, roundtrip: — one per step.
Core lines
for _, target := range []string{
"/srv/app/bin/tool",
"/srv/app/config/app.yaml",
"/var/log/app.log",
} {
rel, err := filepath.Rel(root, target)
if err != nil {
fmt.Println("rel:", err)
continue
}
fmt.Printf("%s -> %s\n", target, rel)
}
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
FAQ
- What does Relative Paths With filepath.Rel print when run?
- The script runs standalone; its 2 labeled outputs include `rel:`, `roundtrip:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.