How to Get Relative Path in Golang

To get the relative path in Go, you can use the “filepath.Rel()” function. The “filepath.Rel()” function takes a base path and a target path and returns the relative path from the base to the target.

Example

package main

import (
  "fmt"
  "path/filepath"
)

func main() {
  base := "/Users/krunallathiya/Desktop/Code/"
  target := "/Users/krunallathiya/Desktop/Code/pythonenv/env/data.txt"
  relativePath, err := filepath.Rel(base, target)
  if err != nil {
    panic(err)
  }
  fmt.Println(relativePath)
}

Output

pythonenv/env/data.txt

In this code, we used the “filepath.Rel()” function to get the relative path from the base path (/Users/krunallathiya/Desktop/Code/pythonenv/env) to the target path (/Users/krunallathiya/Desktop/Code/pythonenv/env/data.txt).

The function returns the relative path (pythonenv/env/data.txt) and an error, which we check for and handle with a panic statement.

Note that the base path must be “absolute”, while the target path can be either an absolute or a relative path. If the target path is relative, it will be interpreted relative to the current working directory.

Also, you can use the “filepath.Clean()” function to normalize the paths by removing any unnecessary . and .. components.

Leave a Comment