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.

Process flow diagram of Abs() function

Process flow diagram of Abs() function

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

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.