0

I'm trying to compile a go package using exec.Command. I was successful with the arguments being "go" and "build" as such below:

package main

import (
    "fmt"
    "log"
    "os/exec"
)

func main() {
    out, err := exec.Command("go", "build").Output()
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(out)
}

However, while trying to perform a "go build" with more arguments it seems that I'm doing something wrong? This is what my code looks like:

package main

import (
    "fmt"
    "log"
    "os/exec"
)

func main() {
    out, err := exec.Command("set", "GOOS=js&&", "set", "GOARCH=wasm&&", "go", "build", "-o", "C:/Users/Daniel/Desktop/go-workspace/src/sandbox/other/wasm/assets/json.wasm", "kard").Output()
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(out)
}

The output is exec: "set": executable file not found in %PATH%

The normal command I would perform for this in the command line would be set GOOS=js&& set GOARCH=wasm&& go build -o C:\Users\Daniel\Desktop\go-workspace\src\sandbox\other\wasm\assets\json.wasm kard.

I assume there is something I'm misunderstanding with using exec.Command? I really appreciate any support.

1 Answer 1

6

The application uses shell syntax to set the environment variables, but the exec package does not use a shell (unless the command that you are running is a shell).

Use the command environment to specify the environment variables for the exec'ed command.

The go build does not normally write to stdout, but it does write errors to stderr. Use CombinedOutput instead of Output to easily capture error text.

cmd := exec.Command("go", "build", "-o", "C:/Users/Daniel/Desktop/go-workspace/src/sandbox/other/wasm/assets/json.wasm", "kard")
cmd.Env = []string{"GOOS=js", "GOARCH=wasm"}
out, err := cmd.CombinedOutput()
if err != nil {
    fmt.Printf("%v: %s\n", err, out)
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the help, but this seems to not properly function either for some reason. It errors out and outputs: exit status 1 (from the response to the cmd) and nothing is compiled.
@Gradesh Find out what the go command is complaining about using the information in the updated answer.
Yup that did it! Was able to debug the error and is working now :). Love you <3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.