Go rules for Bazel
Go rules for Bazel_ =====================
.. Links to external sites and pages .. //tests/core/cross: https://github.com/bazelbuild/rulesgo/blob/master/tests/core/cross/BUILD.bazel .. _Avoiding conflicts: proto/core.rst#avoiding-conflicts .. _Bazel labels: https://docs.bazel.build/versions/master/build-ref.html#labels .. _Bazel: https://bazel.build/ .. _Bazel Tutorial\: Build a Go Project: https://bazel.build/start/go .. _Build modes: go/modes.rst .. _Bzlmod: https://bazel.build/external/overview#bzlmod .. _Go with Bzlmod: docs/go/core/bzlmod.md .. _Go with WORKSPACE: docs/go/core/workspace.md .. _Core rules: docs/go/core/rules.md .. _Coverage: https://bazel.build/configure/coverage .. _Dependencies: go/dependencies.rst .. Deprecation schedule: https://github.com/bazelbuild/rulesgo/wiki/Deprecation-schedule .. _Editor setup instructions: docs/editors.md .. examples/basicgazelle: examples/basic_gazelle .. _examples/hello: examples/hello .. _Gopher Slack: https://invite.slack.golangbridge.org/ .. _gopls integration: docs/editors.md .. _Overriding dependencies: go/dependencies.rst#overriding-dependencies .. _Proto rules: proto/core.rst .. _Protocol buffers: proto/core.rst .. _Toolchains: go/toolchains.rst .. Using rulesgo on Windows: windows.rst .. _bazel-go-discuss: https://groups.google.com/forum/#!forum/bazel-go-discuss .. _configuration transition: https://docs.bazel.build/versions/master/skylark/lib/transition.html .. _gazelle update-repos: https://github.com/bazelbuild/bazel-gazelle#update-repos .. _gazelle: https://github.com/bazelbuild/bazel-gazelle .. _github.com/bazelbuild/bazel-gazelle: https://github.com/bazelbuild/bazel-gazelle .. github.com/bazelbuild/rulesgo/go/tools/bazel: https://pkg.go.dev/github.com/bazelbuild/rules_go/go/tools/bazel?tab=doc .. _nogo build-time static analysis: go/nogo.rst .. _nogo: go/nogo.rst .. rulesgo and Gazelle roadmap: https://github.com/bazelbuild/rules_go/wiki/Roadmap .. _#bazel on Go Slack: https://gophers.slack.com/archives/C1SCQE54N .. _#go on Bazel Slack: https://bazelbuild.slack.com/archives/CDBP88Z0D
.. Go rules .. gobinary: docs/go/core/rules.md#go_binary .. gocontext: go/toolchains.rst#go_context .. godeps: https://github.com/bazel-contrib/bazel-gazelle/blob/master/extensions.md#go_deps .. godownloadsdk: go/toolchains.rst#godownload_sdk .. gohostsdk: go/toolchains.rst#gohost_sdk .. golibrary: docs/go/core/rules.md#go_library .. golocalsdk: go/toolchains.rst#golocal_sdk .. gopath: docs/go/core/rules.md#go_path .. goprotocompiler: proto/core.rst#goproto_compiler .. goprotolibrary: proto/core.rst#goproto_library .. goregistertoolchains: go/toolchains.rst#goregister_toolchains .. gorepository: https://github.com/bazelbuild/bazel-gazelle/blob/master/reference.md#go_repository .. gorulesdependencies: go/dependencies.rst#gorules_dependencies .. gosource: docs/go/core/rules.md#go_source .. gotest: docs/go/core/rules.md#go_test .. gocrossbinary: docs/go/core/rules.md#gocross_binary .. gotoolchain: go/toolchains.rst#go_toolchain .. gowrapsdk: go/toolchains.rst#gowrap_sdk .. _gomock: docs/go/extras/extras.md#gomock
.. External rules .. gitrepository: https://docs.bazel.build/versions/master/repo/git.html .. httparchive: https://docs.bazel.build/versions/master/repo/http.html#http_archive .. protolibrary: https://github.com/bazelbuild/rules_proto
.. Issues .. #265: https://github.com/bazelbuild/rulesgo/issues/265 .. #721: https://github.com/bazelbuild/rulesgo/issues/721 .. #889: https://github.com/bazelbuild/rulesgo/issues/889 .. #1199: https://github.com/bazelbuild/rulesgo/issues/1199 .. #2775: https://github.com/bazelbuild/rulesgo/issues/2775
Mailing list: bazel-go-discuss_
Slack: #go on Bazel Slack, #bazel on Go Slack
Contents
Overview_Setup_FAQ_
Core rules_
gobinary
* golibrary
* gotest
* gosource
* gopath
* gocrossbinary_
Proto rules_
goprotolibrary_
* goprotocompiler_
Dependencies_
gorulesdependencies_
* gorepository (Gazelle)
Toolchains_
goregistertoolchains_
* godownloadsdk_
* gohostsdk_
* golocalsdk_
* gowrapsdk_
* gotoolchain
* gocontext
Extra rules <docs/go/extras/extras.md>_
gomock_
nogo build-time static analysis_Build modes <go/modes.rst>_
Editor setup instructions_rulesgo and Gazelle roadmapDeprecation schedule_Using rulesgo on Windows
These rules support:
- Building libraries, binaries, and tests (
golibrary,gobinary,
gotest)
- Go modules via
godeps. - Vendoring
- cgo
- Cross-compilation
- Generating BUILD files via gazelle_
- Build-time static code analysis via nogo_
Protocol buffers_- Remote execution
Coverage_gopls integration_ for editor support- Debugging
- C/C++ integration other than cgo (SWIG)
- Linux, macOS, Windows
- amd64, arm64
Note: Since version v0.51.0, rules_go requires Bazel ≥ 6.5.0 to work.
The `master branch is only guaranteed to work with the latest version of Bazel.
Setup
To build Go code with Bazel, you will need:
- A recent version of Bazel.
- A C/C++ toolchain (if using cgo). Bazel will attempt to configure the
- Bash,
patch,cat, and a handful of other Unix tools inPATH.
See Using rulesgo on Windows for Windows-specific setup instructions. Several additional tools need to be installed and configured.
If you're new to Bazel, read Bazel Tutorial: Build a Go Project_, which introduces Bazel concepts and shows you how to set up a small Go workspace to be built with Bazel.
For a quicker "hello world" example, see examples/hello_.
For an example that generates build files and retrieves external dependencies using Gazelle, see examples/basicgazelle.
For more detailed Bzlmod documentation, see Go with Bzlmod.
For legacy WORKSPACE instructions, see Go with WORKSPACE_.
FAQ
Go
- Can I still use the go command?
_ - Does this work with Go modules?
_ - What's up with the godefaultlibrary name?
_ - How do I cross-compile?
_ - How do I access testdata?
_ - How do I access gobinary executables from gotest?
_
- How do I avoid conflicts with protocol buffers?
_ - Can I use a vendored gRPC with goprotolibrary?
_
- How do I use different versions of dependencies?
_ - How do I test a beta version of the Go SDK?
_
Yes, but not directly.
rules_go invokes the Go compiler and linker directly, based on the targets described with gobinary and other rules. Bazel and rules_go together fill the same role as the go command, so it's not necessary to use the go command in a Bazel workspace.
That said, it's usually still a good idea to follow conventions required by the go command (e.g., one package per directory, package paths match directory paths). Tools that aren't compatible with Bazel will still work, and your project can be depended on by non-Bazel projects.
If you need to use the go command to perform tasks that Bazel doesn't cover (such as adding a new dependency to go.mod), you can use the following Bazel invocation to run the go binary of the Bazel-configured Go SDK:
.. code:: bash
bazel run @iobazelrules_go//go -- <args>
Prefer this to running go directly since it ensures that the version of Go is identical to the one used by rules_go.
Does this work with Go modules? ~~~~~~~
Yes, but not directly. Bazel ignores go.mod files, and all package dependencies must be expressed through deps attributes in targets described with golibrary and other rules.
You can download a Go module at a specific version as an external repository using gorepository, a workspace rule provided by gazelle_. This will also generate build files using gazelle_.
You can import gorepository rules from a go.mod file using gazelle update-repos_.
What's up with the godefaultlibrary name? ~~~~~~~~~~~
This was used to keep import paths consistent in libraries that can be built with go build before the importpath attribute was available.
In order to compile and link correctly, rules_go must know the Go import path (the string by which a package can be imported) for each library. This is now set explicitly with the importpath attribute. Before that attribute existed, the import path was inferred by concatenating a string from a special go_prefix rule and the library's package and label name. For example, if go_prefix was github.com/example/project, for a library //foo/bar:bar, rules_go would infer the import path as github.com/example/project/foo/bar/bar. The stutter at the end is incompatible with go build, so if the label name was godefaultlibrary, the import path would not include it. So for the library //foo/bar:godefaultlibrary, the import path would be github.com/example/project/foo/bar.
Since go_prefix was removed and the importpath attribute became mandatory (see #721), the godefault_library name no longer serves any purpose. We may decide to stop using it in the future (see #265_).
How do I cross-compile? ~~~~~~~
You can cross-compile by setting the --platforms flag on the command line. For example:
.. code::
$ bazel build --platforms=@iobazelrulesgo//go/toolchain:linuxamd64 //cmd
By default, cgo is disabled when cross-compiling. To cross-compile with cgo, add a _cgo suffix to the target platform. You must register a cross-compiling C/C++ toolchain with Bazel for this to work.
.. code::
$ bazel build --platforms=@iobazelrulesgo//go/toolchain:linuxamd64_cgo //cmd
Platform-specific sources with build tags or filename suffixes are filtered automatically at compile time. You can selectively include platform-specific dependencies with select expressions (Gazelle does this automatically).
.. code:: bzl
go_library( name = "foo", srcs = [ "foo_linux.go", "foo_windows.go", ], deps = select({ "@iobazelrulesgo//go/platform:linuxamd64": [ "//bar_linux", ], "@iobazelrulesgo//go/platform:windowsamd64": [ "//bar_windows", ], "//conditions:default": [], }), )
To build a specific gobinary target for a target platform or using a specific golang SDK version, use the gocrossbinary_ rule. This is useful for producing multiple binaries for different platforms in a single build.
To build a specific gotest target for a target platform, set the goos and goarch attributes on that rule.
You can equivalently depend on a gobinary or gotest rule through a Bazel configuration transition on //commandline_option:platforms (there are problems with this approach prior to rules_go 0.23.0).
How do I access testdata? ~~~~~
Bazel executes tests in a sandbox, which means tests don't automatically have access to files. You must include test files using the data attribute. For example, if you want to include everything in the testdata directory:
.. code:: bzl
go_test( name = "foo_test", srcs = ["foo_test.go"], data = glob(["testdata/**"]), importpath = "github.com/example/project/foo", )
By default, tests are run in the directory of the build file that defined them. Note that this follows the Go testing convention, not the Bazel convention followed by other languages, which run in the repository root. This means that you can access test files using relative paths. You can change the test directory using the rundir attribute. See gotest.
Gazelle will automatically add a data attribute like the one above if you have a testdata directory unless it contains buildable .go files or build files, in which case, testdata is treated as a normal package.
Note that on Windows, data files are not directly available to tests, since test data files rely on symbolic links, and by default, Windows doesn't let unprivileged users create symbolic links. You can use the github.com/bazelbuild/rulesgo/go/tools/bazel library to access data files.
How do I access gobinary executables from gotest? ~~~~~~~~~~~
The location where go_binary writes its executable file is not stable across rules_go versions and should not be depended upon. The parent directory includes some configuration data in its name. This prevents Bazel's cache from being poisoned when the same binary is built in different configurations. The binary basename may also be platform-dependent: on Windows, we add an .exe extension.
To depend on an executable in a go_test rule, reference the executable in the data attribute (to make it visible), then expand the location in args. The real location will be passed to the test on the command line. For example:
.. code:: bzl
go_binary( name = "cmd", srcs = ["cmd.go"], )
go_test( name = "cmd_test", srcs = ["cmd_test.go"], args = ["$(location :cmd)"], data = [":cmd"], )
See //tests/core/cross_ for a full example of a test that accesses a binary.
Alternatively, you can set the out attribute of gobinary to a specific filename. Note that when out is set, the binary won't be cached when changing configurations.
.. code:: bzl
go_binary( name = "cmd", srcs = ["cmd.go"], out = "cmd", )
go_test( name = "cmd_test", srcs = ["cmd_test.go"], data = [":cmd"], )
How do I avoid conflicts with protocol buffers? ~~~~~~~~~~~
See Avoiding conflicts_ in the proto documentation.
Can I use a vendored gRPC with goprotolibrary? ~~~~~~~~~~~~
This is not supported. When using goprotolibrary_ with the @iobazelrulesgo//proto:gogrpc compiler, an implicit dependency is added on @orggolanggooglegrpc//:godefault_library. If you link another copy of the same package from //vendor/google.golang.org/grpc:godefaultlibrary or anywhere else, you may experience conflicts at compile or run-time.
If you're using Gazelle with proto rule generation enabled, imports of google.golang.org/grpc will be automatically resolved to @orggolanggooglegrpc//:godefault_library to avoid conflicts. The vendored gRPC should be ignored in this case.
If you specifically need to use a vendored gRPC package, it's best to avoid using goprotolibrary altogether. You can check in pre-generated .pb.go files and build them with go_library rules. Gazelle will generate these rules when proto rule generation is disabled (add # gazelle:proto disable_global to your root build file).
How do I use different versions of dependencies? ~~~~~~~~~~~~
See Overriding dependencies_ for instructions on overriding repositories declared in gorulesdependencies_.
How do I test a beta version of the Go SDK? ~~~~~~~~~~~
rules_go only supports official releases of the Go SDK. However, you can still test beta and RC versions by passing a version like "1.16beta1" to goregistertoolchains. See also godownloadsdk`.
.. code:: bzl
load("@iobazelrulesgo//go:deps.bzl", "goregistertoolchains", "gorules_dependencies")
gorulesdependencies()
goregistertoolchains(version = "1.17beta1")