Discover Go commands and flags
Discover Go commands and flags
Use the go command as the entry point to building, running, testing and inspecting packages. go help lists commands; go help build, go help testflag and go tool expose different layers of the toolchain. Check the installed version before copying commands from another release. Prefer structured output (go env -json, go list -json) to scraping text intended for humans. The following program queries the installed toolchain without modifying its settings.
package main
import ( "encoding/json" "fmt" "os/exec")
func main() { out, err := exec.Command("go", "env", "-json", "GOOS", "GOARCH").Output() if err != nil { panic(err) } var v map[string]string if err = json.Unmarshal(out, &v); err != nil { panic(err) } fmt.Println(v["GOOS"] != "", v["GOARCH"] != "")}Both values are present; their actual values vary by target. GOOS and GOARCH describe the build target, which need not equal the host. A CLI failure is not an empty successful result: inspect the error before parsing. go build ./... checks packages without running their tests; go test ./... compiles and executes tests; go run . runs a main package. go vet ./... reports selected suspicious constructs, not all bugs.
Expected output:
true trueInspect a known package
package main
import ( "encoding/json" "fmt" "os/exec")
func main() { out, err := exec.Command("go", "list", "-json", "fmt").Output() if err != nil { panic(err) } var p struct { ImportPath string Standard bool } if err = json.Unmarshal(out, &p); err != nil { panic(err) } fmt.Println(p.ImportPath, p.Standard)}Run commands in a deliberate working directory. go list may resolve modules; restrict the examples to the standard library or an offline module when network access is undesired. Use go test -run to select tests, -count=1 to avoid cached test results, and go help buildconstraint for target selection. Do not pass an untrusted string to a shell just to run go.
Expected output:
fmt trueTry it locally
Query go env -json GOVERSION; decode the field and verify that it starts with go. Do not hard-code the patch version.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Toolchain and compatibility 01: Discover Go commands and flags
Check the lesson objective before moving on.
Which command runs tests in a package tree?
Why use go list -json in an automation?