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.

Krunal Lathiya is a Software Engineer with over eight years of experience. He has developed a strong foundation in computer science principles and a passion for problem-solving. In addition, Krunal has excellent knowledge of Distributed and cloud computing and is an expert in Go Language.