Programmatic way to call go tools

Viewed 1217

Is there a way to call the Go tools (like go build) programmatically from within another Go program with a library call and to get more structured output compared to the text output from the command line invocation?

2 Answers

If you're trying to run build programmatically you can also use the os/exec package.

func runBuild() {
    cmd := exec.Command("go", "build", "./main.go")
    err := cmd.Run()
    if err != nil {
        log.Fatal(err)
    }

}

You can pass other flags too. E.g: the buildmode flag

cmd := exec.Command("go", "build", "-buildmode=plugin", "./main.go")

Reference: https://golang.org/pkg/os/exec/

Related