Changing GOOS and GOARCH in code

Hello!

Today I started working on a web app to automatically build and store releases that I could submit, for all operating systems and architectures. I stumbled upon an issue which I couldn’t solve myself.

So I wanted to go build for each operating system, and tried setting the GOOS and GOARCH in the Default context in the build package, then using exec.Command(“go”, “build”). All seemed well, but it turned out it would all just build the same executable, for windows.

I’m out of ideas, and don’t know how to build with a different GOOS and GOARCH inside of Go code. I hope someone can help me with it.

Thanks in advance,
Sander

If you are using exec.Command, set the environment variables before running. The quick and dirty way:

os.Setenv("GOOS", "linux")
os.Setenv("GOARCH", "amd64")
cmd := exec.Command("go", "build", "./cmd/whatever")
err := cmd.Run() // and so on

To do it with more precision, set the Env attribute on cmd before running it, copying the stuff you want to retain from the current os.Environ.

1 Like

Thank you very much. That’s exactly what I needed!

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.