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.

GoCli Tooling

Code

gosnippet
28 lines
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

FAQ

What does Relative Paths With filepath.Rel print when run?
The script runs standalone; its 2 labeled outputs include `rel:`, `roundtrip:`.