I Spy Code - GO

Relative path from basepath

Question:

How to get a relative path of a target path from a base path in golang?

Answer:

The function filepath.Rel() returns a relative path that is lexically equivalent to target path when joined to base path with an intervening separator.

Here is a golang example that shows how to get a relative path of a target path from a base path:

Source: (example.go)

package main
 
import (
   "fmt"
   "path/filepath"
)
 
func main(){
 
 
   targpath := "/home/dennis/projects"
   basepath := "/home/dennis/projects/golang/file1"
 
   relpath, _ := filepath.Rel(targpath,basepath)
   fmt.Println("Relative Path:", relpath)
}
 

Output:

$ go run example.go
Relative Path:  golang/file1

References:

https://golang.org/pkg/path/filepath/#Rel