How to Get Relative Path in Golang

Relative paths tell the file’s location with respect to the present working directory, whereas absolute paths tell the file’s location starting from the root directory.

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.

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 absolute or relative. 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.

Related posts

How to Get the Current Working Directory in Go

Import Local Packages without Gopath in Go

List the Contents of a Directory in Go