How to Get Absolute Path in Golang

To get the absolute path of a file or directory in Golang, you can use the “filepath.Abs()” function. The filepath.Abs() is a built-in function that accepts a path and returns “an absolute representation of the specified path”.

An absolute path is a complete path to a file or directory that confines the exact location of the file or directory on a computer. It starts from the file system’s root directory and includes all the intermediate directories, subdirectories, and the file’s name or directory.

Syntax

func Abs(path string) (string, error)

Parameters

The “path” is the specified path.

Return value

It returns an absolute representation of the specified path.

Example 1

package main

import (
  "fmt"
  "path/filepath"
)

func main() {
  absPath, err := filepath.Abs("../file.txt")
  if err != nil {
    panic(err)
  }

  // Print the absolute path of the file
  fmt.Println(absPath)
}

Output

/Users/krunallathiya/Desktop/Code/R/file.txt

We imported the fmt and path/filepath packages, which print the file’s absolute path and get the file’s absolute path, respectively.

In the next part, we use the filepath.Abs() function to get the absolute path of the file.txt file.

The filepath.Abs() function can raise an error, so we use an if statement to check for errors.

Finally, we used the fmt.Println() function to print the absolute path of the file. It allows us to see the file’s absolute path and verify it is correct.

Example 2

package main

import (
  "fmt"
  "path/filepath"
)

func main() {
  fmt.Println(filepath.Abs("/"))
  fmt.Println(filepath.Abs("."))
  fmt.Println(filepath.Abs(":"))
  fmt.Println(filepath.Abs("/."))
  fmt.Println(filepath.Abs("//"))
  fmt.Println(filepath.Abs(":/"))
}

Output

/ <nil>
/Users/krunallathiya/Desktop/Code/pythonenv/env <nil>
/Users/krunallathiya/Desktop/Code/pythonenv/env/: <nil>
/ <nil>
/ <nil>
/Users/krunallathiya/Desktop/Code/pythonenv/env/: <nil>

That’s it.

Leave a Comment