Skip to content

Instantly share code, notes, and snippets.

@geberl
Created October 28, 2019 07:43
Show Gist options
  • Save geberl/2419d58b68bbbb289fa19c7e421278a1 to your computer and use it in GitHub Desktop.
Save geberl/2419d58b68bbbb289fa19c7e421278a1 to your computer and use it in GitHub Desktop.
Reliably access a file that resides next to the code/binary, whether it's started via go run or go build
package main
import (
"fmt"
"os"
log "github.com/sirupsen/logrus"
)
func main() {
p := getCorrectPath
fmt.Println(p)
}
func getCorrectPath(filename string) string {
// Example: A file resides in the src directory, next to the code
// IF compiled via `go build ...` and then invoked via program start
// The file should then reside next to the "main" executable
// os.Executable() points to the executable, everything is fine
// IF invoked via `go run ...` from current working dir "src/"
// In this case the file can NOT be found next to the executable
// os.Executable() points to a temporary directory like "/var/folders/h8/yc69bl5x56n4772z7yyw1xj00000gn/T/go-build682711541/b001/exe/..."
// So here filepath.Abs("./") has to be used
// A side effect is that this does not work if started from other pwd than "src"
exPath, err := os.Executable()
FailOnError(err, "Can't get path to the executable")
crossPlatformPath := filepath.FromSlash(filepath.Dir(exPath) + "/" + filename)
if _, err := os.Stat(crossPlatformPath); os.IsNotExist(err) {
log.WithFields(log.Fields{
"crossPlatformPath": crossPlatformPath,
"executablePath": exPath,
"filename": filename,
}).Warning("File not found at preferred location")
exPath, err = filepath.Abs("./")
FailOnError(err, "Can't get path to the executable")
crossPlatformPath = filepath.FromSlash(exPath + "/" + filename)
if _, err := os.Stat(crossPlatformPath); os.IsNotExist(err) {
log.WithFields(log.Fields{
"crossPlatformPath": crossPlatformPath,
"executablePath": exPath,
"filename": filename,
}).Fatal("File not found at alternate location")
}
}
log.WithFields(log.Fields{
"crossPlatformPath": crossPlatformPath,
"executablePath": exPath,
"filename": filename,
}).Info("File found")
return crossPlatformPath
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment