Browse Source

Implement search path lookup in a local method

master
jimi 9 years ago
parent
commit
f7aa510901
  1. 10
      README.md
  2. 16
      main.go

10
README.md

@ -2,8 +2,12 @@
Examples of methods for determining the directory path where our executable resides. Examples of methods for determining the directory path where our executable resides.
- The `kardianos/osext` package is used for reference. The other methods will
require that the executable is located within the OS search path.
- The `github.com/kardianos/osext` package is used for reference. The other methods
will require that the executable is located within the OS search path.
- The first alternative utilizes `exec.LookPath` to find the executable within the - The first alternative utilizes `exec.LookPath` to find the executable within the
OS search path.
OS search path. This method depends on the `os`, `os/exec`, and `path` packages.
- The next method defines a local function to look for the file named in `args[0]`
in the directories listed in the `PATH` environment variable. This method depends
on the `os` and `strings` packages.

16
main.go

@ -6,6 +6,7 @@ import (
"os" "os"
"os/exec" "os/exec"
"path" "path"
"strings"
"github.com/kardianos/osext" "github.com/kardianos/osext"
) )
@ -29,7 +30,22 @@ func main() {
} }
lookPath := path.Dir(exePath) lookPath := path.Dir(exePath)
// Walk the path environment locally
walkPath := pathWalker(os.Args[0])
// Output to comapre the results // Output to comapre the results
fmt.Printf("osext.ExeFolder : %s\n", exeFolder) fmt.Printf("osext.ExeFolder : %s\n", exeFolder)
fmt.Printf("exec.LookPath : %s\n", lookPath) 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"
} }
Loading…
Cancel
Save