How to Get the Directory of the Currently Running File in Go

Created
Modified

Using os.Executable Function

Executable returns the path name for the executable that started the current process.

The easiest way to get the directory of the currently running file in Golang:

package main

import (
  "fmt"
  "os"
  "path/filepath"
)

func main() {

  exec, err := os.Executable()
  if err != nil {
    // panic()
  }
  dir := filepath.Dir(exec)
  fmt.Println(dir)
}
/data/golang

Using os.Getwd Function

Getwd returns a rooted path name corresponding to the current directory. For example,

package main

import (
  "fmt"
  "os"
)

func main() {

  pwd, err := os.Getwd()
  if err != nil {
    // panic()
  }
  fmt.Println(pwd)
}
/data/golang

Using Command-line Arguments

Command-line arguments are a common way to parameterize execution of programs. Sometimes this is enough, the first argument will always be the file path:

package main

import (
  "fmt"
  "os"
)

func main() {

  path := os.Args[0]
  fmt.Println(path)
}
./backend

Doesn't always work well.

Related Tags