Exercise in determining from whence we came.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

51 lines
1.0 KiB

package main
import (
"fmt"
"log"
"os"
"os/exec"
"path"
"strings"
"github.com/kardianos/osext"
)
func main() {
// Find location of executable with kardianos/osext
exeFolder, err := osext.ExecutableFolder()
if err != nil {
log.Fatal(err)
}
//
// These will require that the executable is in a directory within the $PATH
// Find location of executable with Args[0] and exec.LookPath
// Requires import of os, os/exec, and path
argZero := os.Args[0]
exePath, err := exec.LookPath(argZero)
if err != nil {
log.Fatal(err)
}
lookPath := path.Dir(exePath)
// Walk the path environment locally
walkPath := pathWalker(os.Args[0])
// Output to comapre the results
fmt.Printf("osext.ExeFolder : %s\n", exeFolder)
fmt.Printf("exec.LookPath : %s\n", lookPath)
fmt.Printf("local walkPath : %s\n", walkPath)
}
func pathWalker(file string) string {
path := os.Getenv("PATH")
for _, dir := range strings.Split(path, ":") {
exe := dir + "/" + file
if _, err := os.Stat(exe); err == nil {
return dir
}
}
return "not found"
}