How to Get Absolute Path in Golang

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.

An absolute path always starts from the root directory of the file system. It includes all the intermediate directories, subdirectories, and the file’s name or directory.

A relative path is a path to a file or directory relative to the current directory. A relative path does not contain the complete path to the file or directory but specifies the path to the file or directory relative to the current directory.

In this tutorial, we will discuss an absolute path in Golang and how to get it.

How to Get the Absolute Path in Golang

To get the absolute path of a file or directory in Golang, use the filepath.Abs() function. The filepath.Abs() is a built-in function that accepts a path as input and returns the file’s absolute path or directory.

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 are used to 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 use the fmt.Println() function to print the absolute path of the file. It allows us to see the file’s absolute path and verify that it is correct.

Conclusion

The easiest and most efficient way to get an absolute path in Go is to use the filePath.Abs() function.

Leave a Comment