Go: go_library, go_binary, go_test
rules_go (0.65.0 here) builds Go without the go command: it calls the Go compiler and linker directly, one action per package, so Bazel can cache and parallelise every package and mix Go with other languages. You give up go build's automatic discovery and write the dependencies down, usually with the help of Gazelle, which generates the BUILD files from your imports.
| Rule | Purpose | Key attributes |
|---|---|---|
go_library |
one Go package | srcs, deps, importpath (the path other packages import) |
go_binary |
a package main program |
srcs, deps, embed, x_defs, pure, static, goos/goarch |
go_test |
a package's tests | srcs, embed = [":lib"] for internal tests, deps for external tests |
The Go SDK comes from a module extension, so every machine compiles with the same Go:
go_sdk = use_extension("@rules_go//go:extensions.bzl", "go_sdk")
go_sdk.download(version = "1.27.3")A service with a library and tests
mkdir ws && cd ws
cat > MODULE.bazel <<'EOF'
module(name = "shop")
bazel_dep(name = "rules_go", version = "0.65.0")
go_sdk = use_extension("@rules_go//go:extensions.bzl", "go_sdk")
go_sdk.download(version = "1.27.3")
EOF
mkdir -p pricing cmd/pricer
cat > pricing/BUILD.bazel <<'EOF'
load("@rules_go//go:def.bzl", "go_library", "go_test")
go_library(
name = "pricing",
srcs = ["pricing.go"],
importpath = "example.com/shop/pricing",
visibility = ["//visibility:public"],
)
go_test(
name = "pricing_test",
size = "small",
srcs = ["pricing_test.go"],
embed = [":pricing"],
)
EOF
cat > pricing/pricing.go <<'EOF'
package pricing
// WithTax returns the price in cents including the tax rate given in percent.
func WithTax(cents, percent int) int {
return cents + cents*percent/100
}
EOF
cat > pricing/pricing_test.go <<'EOF'
package pricing
import "testing"
func TestWithTax(t *testing.T) {
if got := WithTax(1000, 8); got != 1080 {
t.Fatalf("WithTax(1000, 8) = %d, want 1080", got)
}
}
EOF
cat > cmd/pricer/BUILD.bazel <<'EOF'
load("@rules_go//go:def.bzl", "go_binary")
go_binary(
name = "pricer",
srcs = ["main.go"],
deps = ["//pricing"],
x_defs = {"main.version": "1.4.0"},
)
EOF
cat > cmd/pricer/main.go <<'EOF'
package main
import (
"fmt"
"runtime"
"example.com/shop/pricing"
)
var version = "dev"
func main() {
fmt.Printf("pricer %s (%s): 1999 cents + 10%% = %d cents\n", version, runtime.Version(), pricing.WithTax(1999, 10))
}
EOF
bazel run //cmd/pricer 2>&1 | grep -E '^INFO: [0-9]+ process|^pricer '
bazel test //pricing:pricing_test 2>&1 | grep -E 'PASSED|FAILED'
bazel run //cmd/pricer 2>&1 | grep -E '^INFO: [0-9]+ process'INFO: 13 processes: 8 internal, 5 processwrapper-sandbox.
pricer 1.4.0 (go1.27.3): 1999 cents + 10% = 2198 cents
//pricing:pricing_test PASSED in 0.0s
INFO: 1 process: 7 action cache hit, 1 internal.
What happened:
- The first build compiled the Go standard library for this configuration (rules_go builds it from source once per configuration, which takes about half a minute here), then the two packages, then linked.
importpathis the bridge between Go and Bazel: the source saysimport "example.com/shop/pricing", the BUILD file saysdeps = ["//pricing"], and rules_go checks that the dependency'simportpathmatches. A missing dep is a compile error naming the import.x_defssets a string variable at link time, likego build -ldflags "-X main.version=1.4.0"(Version Stamping shows thegoway). With--stamp, values such as{STABLE_GIT_COMMIT}can come from a workspace status script.- The test reused the compiled standard library, and the last
bazel runran no compile at all.
Where things go
mkdir ws && cd ws
cat > MODULE.bazel <<'EOF'
bazel_dep(name = "rules_go", version = "0.65.0")
go_sdk = use_extension("@rules_go//go:extensions.bzl", "go_sdk")
go_sdk.download(version = "1.27.3")
EOF
mkdir hello
printf 'load("@rules_go//go:def.bzl", "go_binary")\ngo_binary(name = "hello", srcs = ["main.go"], pure = "on", static = "on")\n' > hello/BUILD.bazel
printf 'package main\n\nimport "fmt"\n\nfunc main() { fmt.Println("hi") }\n' > hello/main.go
bazel build //hello 2>&1 | sed -n '/up-to-date/,+1p'
file -b bazel-bin/hello/hello_/hello | cut -d, -f1,2,4Target //hello:hello up-to-date:
bazel-bin/hello/hello_/hello
ELF 64-bit LSB executable, x86-64, statically linked
go_binary puts the executable in a <name>_/ subdirectory. pure = "on" disables cgo (no C toolchain involved) and static = "on" links statically, which is what you usually want for a container image.
Third-party Go modules (not run here)
External modules come from your go.mod and go.sum through Gazelle's go_deps extension:
bazel_dep(name = "gazelle", version = "0.51.3")
go_deps = use_extension("@gazelle//:extensions.bzl", "go_deps")
go_deps.from_file(go_mod = "//:go.mod")
use_repo(go_deps, "com_github_google_uuid")and BUILD files then use labels such as @com_github_google_uuid//:uuid. go.mod stays the source of truth: you still run go get and go mod tidy (Go Modules in Depth explains them), then bazel mod tidy updates the use_repo list. The course image has no Go module proxy for Bazel and no Gazelle archive, so this part is shown only.
Test yourself
What does importpath on a go_library do?
- Sets the output file name
- Declares the import path Go code uses for this package; rules_go matches it against deps
- Downloads the package
- Sets GOPATH
Why was the first Go build of the session much slower than the second?
- Bazel downloaded Go
- rules_go compiled the Go standard library for the configuration once
- Tests always run twice
- The sandbox was cold
How do you set main.version at link time with rules_go?
x_defs = {"main.version": "1.4.0"}on the go_binary- A genrule that edits main.go
coptsenv