Reputation: 93
I want to know if there is a non OS-specific way to test if a Go program is launched by using the go run
command or by executing the binary produced by the go build
command.
Upvotes: 2
Views: 2362
Reputation: 995
Here is the function I use to get the working directory, whether I run with go run
or whether I build it:
func GetWorkDir() string {
ex, err := os.Executable()
if err != nil {
panic(err)
}
dir := filepath.Dir(ex)
// Helpful when developing:
// when running `go run`, the executable is in a temporary directory.
if strings.Contains(dir, "go-build") {
return "."
}
return filepath.Dir(ex)
}
Upvotes: 4
Reputation: 21035
First: it's always compiled.
Second: There is no guaranteed way to tell the difference between binaries compiled using go build
and go run
.
go run main.go
just builds a temporary binary and executes it.
You can look at the path of the binary being executed by printing os.Args[0]
(the first argument). eg for the following program:
package main
import (
"fmt"
"os"
)
func main() {
fmt.Println(os.Args[0])
}
$ go run main.go
/tmp/go-build854217312/b001/exe/main
$ go build -o main . && ./main
./main
You could try to detect the fact that the first one is in a temporary directory but the location will depend on the OS and is not guaranteed to remain the same across go versions.
Overall, it might not be worth it. go run
is not acceptable for any serious binary, it should always be compiled.
Upvotes: 6