How to get the directory of the current executable file in Go?
Hello everyone! I'm a beginner Go developer and I've run into a problem: I need to determine the directory where the current executable file of my program is located. I'm writing a small CLI application that reads a configuration file located in the same folder as the binary. But when I run the program from a different directory (for example, via `go run` from the project root or from the system PATH), relative paths break.
Here's what I've tried:
```go
package main
import (
"fmt"
"os"
"path/filepath"
)
func main() {
// Attempt 1: just os.Getwd() — gives the working directory, not the file's folder
wd, _ := os.Getwd()
fmt.Println("Working dir:", wd)
// Attempt 2: os.Args[0] — shows the path used to call the program
fmt.Println("Args[0]:", os.Args[0])
// Attempt 3
```
No answers yet.
Log in to leave an answer