Last active
November 13, 2024 17:02
-
-
Save kevsmith/926178595a84c5c93ac4a11aad3e4cc4 to your computer and use it in GitHub Desktop.
Dynamically discover executable path at runtime
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"os" | |
"path/filepath" | |
) | |
func executableLocation() (string, string, error) { | |
// 0th arg traditionally contains name of executable as invoked by the user | |
// Split executable name into directory path and filename parts | |
exeDir, exeFile := filepath.Split(os.Args[0]) | |
// Clean the directory path and convert it to an absolute path | |
// This handles cases where a relative path reference is used | |
// such as "./foo" or "../foo" | |
absoluteExeDir, err := filepath.Abs(filepath.Clean(exeDir)) | |
// Return error if absolute path construction fails | |
if err != nil { | |
return "", "", err | |
} | |
return absoluteExeDir, exeFile, nil | |
} | |
func main() { | |
exeDir, exeFileName, err := executableLocation() | |
if err != nil { | |
panic(err) | |
} | |
fmt.Printf("Executable dir: %s\nExecutable filename: %s\n", exeDir, exeFileName) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
> go build -o discover main/main.go | |
> ./discover | |
Executable dir: /Users/kesmit/repos/experiments/discover | |
Executable filename: discover | |
> go run main/main.go | |
Executable dir: /var/folders/1c/19j1cgwx2ng1gjxj5rypmkwh0000gp/T/go-build3431073968/b001/exe | |
Executable filename: main | |
> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment