Go filepath.Rel
Compute a relative path between locations sharing a base.
A simple example
filepath.Rel
- Start with Start at notes, target notes/a.txt
- Do this Find the relative route
- Result a.txt
Syntax
filepath.Rel(from, target)
Run these examples in Go
Save one example at a time as main.go. Use Go 1.21 or later.
go run main.goLink a course handout to a diagram
A course will move between the teacher’s laptop and the school server. Compute a relative route from its notes folder to a sibling image folder so the handout can still find the same diagram.
package main
import (
"os"
"fmt"
"path/filepath"
)
func check(err error) {
if err != nil { panic(err) }
}
func main() {
dir, err := os.MkdirTemp("", "lesson-")
check(err)
defer os.RemoveAll(dir)
p := func(name string) string { return filepath.Join(dir, name) }
link, err := filepath.Rel(p("notes"), p("images/map.png"))
check(err)
fmt.Println(filepath.ToSlash(link))
}
../images/map.png
Go up one directory from notes, then enter images and select the diagram.
Locate a rehearsal score
The choir stores each score inside a season folder. A catalogue starts in the parent directory. Which relative link reaches the file in the named subfolder? Use forward slashes in this example.
Locate a workshop handout
An instructor stores the current template in a class folder. A catalogue starts in the parent directory. Which relative link reaches the file in the named subfolder? Use forward slashes in this example.
What to watch for
Both paths need compatible roots. The result depends on which directory is the starting point.