### Nogo Rule Configuration Example Source: https://github.com/bazel-contrib/rules_go/blob/master/go/nogo.rst An example demonstrating the nogo rule with dependencies, a configuration file, and enabled vet checks. ```bzl nogo( name = "my_nogo", deps = [ ":importunsafe", ":otheranalyzer", "@analyzers//:unsafedom", ], config = ":config.json", vet = True, visibility = ["//visibility:public"], ) ``` -------------------------------- ### Install gopls Source: https://github.com/bazel-contrib/rules_go/wiki/Editor-setup Installs the gopls language server. Ensure your GOBIN is in your PATH. ```bash $ go install golang.org/x/tools/gopls@v0.7.2 ``` -------------------------------- ### go_library Example Source: https://github.com/bazel-contrib/rules_go/blob/master/docs/go/core/examples.md Defines a Go library with source files, dependencies, import path, and visibility. ```bzl go_library( name = "foo", srcs = [ "foo.go", "bar.go", ], deps = [ "//tools", "@org_golang_x_utils//stuff", ], importpath = "github.com/example/project/foo", visibility = ["//visibility:public"], ) ``` -------------------------------- ### Use Installed Go SDK Source: https://github.com/bazel-contrib/rules_go/blob/master/go/toolchains.rst Configure Bazel to use the Go SDK installed on the host system. This can speed up builds but may reduce reproducibility. ```bzl # WORKSPACE load("@io_bazel_rules_go//go:deps.bzl", "go_rules_dependencies", "go_register_toolchains") go_rules_dependencies() go_register_toolchains(version = "host") ``` -------------------------------- ### Install gopls Source: https://github.com/bazel-contrib/rules_go/blob/master/docs/editors.md Installs the latest version of the gopls binary. Ensure your $GOBIN is in your PATH. ```bash #!/usr/bin/env bash exec bazel run -- @rules_go//go/tools/gopackagesdriver "${@}" ``` -------------------------------- ### Register host Go SDK Source: https://github.com/bazel-contrib/rules_go/blob/master/docs/go/core/bzlmod.md Use `go_sdk.host()` to register the Go SDK installed on the host machine. Note that this method is discouraged due to potential build reproducibility issues if the host Go version is upgraded outside of Bazel's control. ```starlark go_sdk = use_extension("@rules_go//go:extensions.bzl", "go_sdk") # Another alternative is to register the Go SDK installed on the host (see the nota bene below). go_sdk.host() ``` -------------------------------- ### Workspace Status Script Example Source: https://github.com/bazel-contrib/rules_go/blob/master/docs/go/core/defines_and_stamping.md A bash script that outputs build information in a key-value format for Bazel's workspace status. ```bash #!/usr/bin/env bash echo STABLE_GIT_COMMIT $(git rev-parse HEAD) ``` -------------------------------- ### VS Code Editor Setup (Pre-Bzlmod) Source: https://github.com/bazel-contrib/rules_go/wiki/Editor-setup Configure VS Code settings for Go development with rules_go when not using bzlmod. Ensure 'go.goroot' and 'formatting.local' are updated to match your repository's workspace name and import path. ```jsonc { // Settings for go/bazel are based on editor setup instructions at // https://github.com/bazelbuild/rules_go/wiki/Editor-setup#visual-studio-code "go.goroot": "${workspaceFolder}/bazel-${workspaceFolderBasename}/external/rules_go++go_sdk+go_sdk/", "go.toolsEnvVars": { "GOPACKAGESDRIVER": "${workspaceFolder}/tools/gopackagesdriver.sh" }, "go.enableCodeLens": { "runtest": false }, "gopls": { "build.workspaceFiles": [ "**/BUILD", "**/WORKSPACE", "**/*.{bzl,bazel}", ], "build.directoryFilters": [ "-bazel-bin", "-bazel-out", "-bazel-testlogs", "-bazel-mypkg", ], "formatting.gofumpt": true, "formatting.local": "github.com/my/mypkg", "ui.completion.usePlaceholders": true, "ui.semanticTokens": true, "ui.codelenses": { "gc_details": false, "regenerate_cgo": false, "generate": false, "test": false, "tidy": false, "upgrade_dependency": false, "vendor": false }, }, "go.useLanguageServer": true, "go.buildOnSave": "off", "go.lintOnSave": "off", "go.vetOnSave": "off", } ``` -------------------------------- ### Nogo Rule Configuration Source: https://github.com/bazel-contrib/rules_go/blob/master/go/nogo.rst Example of how to configure the nogo rule with a custom configuration file. ```APIDOC ## nogo Rule ### Description This rule generates a program that analyzes the source code of Go programs, running alongside the Go compiler in Bazel to reject programs with disallowed coding patterns. ### Attributes #### name - **Type**: string - **Default value**: mandatory - **Description**: A unique name for this rule. #### deps - **Type**: label_list - **Default value**: None - **Description**: List of Go libraries that will be linked to the generated nogo binary. These libraries must declare an `analysis.Analyzer` variable named `Analyzer`. #### config - **Type**: label - **Default value**: None - **Description**: JSON configuration file that configures one or more of the analyzers in `deps`. #### vet - **Type**: bool - **Default value**: False - **Description**: If true, a safe subset of vet checks will be run by nogo (the same subset run by `go test`). ### Example ```bzl nogo( name = "my_nogo", deps = [ ":importunsafe", ":otheranalyzer", "@analyzers//:unsafedom", ], config = ":config.json", vet = True, visibility = ["//visibility:public"], ) ``` ``` -------------------------------- ### Basic C/C++ Workspace Setup for Bazel on Windows Source: https://github.com/bazel-contrib/rules_go/blob/master/windows.rst This snippet defines a minimal Bazel workspace with a C++ binary target. It includes the WORKSPACE, BUILD.bazel, and a simple C source file. Ensure these files are placed in the correct locations within your Bazel workspace. ```bazel -- WORKSPACE -- -- BUILD.bazel -- cc_binary( name = "hello", srcs = ["hello.c"], ) -- hello.c -- #include int main() { printf("hello\n"); return 0; } ``` -------------------------------- ### Apply nogo Fixes with Bazel Source: https://github.com/bazel-contrib/rules_go/blob/master/go/nogo.rst These commands demonstrate how to run nogo to generate patch files and then apply those fixes using Bazel and standard shell utilities. Ensure you have the necessary Bazel flags and tools installed. ```shell # Only run nogo, no compilation actions, and don't fail on findings. bazel build //... --norun_validations --output_groups nogo_fix --remote_download_regex='.*/nogo.patch$' # Apply all fixes. bazel cquery //... --norun_validations --output_groups nogo_fix --remote_download_regex='.*/nogo.patch$' --output=files \ | xargs -I{} sh -c '[[ ! -e {}/nogo.patch ]] || patch -p1 -N --reject-file /dev/null < {}/nogo.patch' ``` -------------------------------- ### Initialize Go Module Source: https://github.com/bazel-contrib/rules_go/blob/master/docs/go/core/bzlmod.md Create an initial `go.mod` file for your project using `bazel run @rules_go//go mod init`. ```sh bazel run @rules_go//go mod init github.com/example/project ``` -------------------------------- ### Run the Go Binary with Bazel Source: https://github.com/bazel-contrib/rules_go/blob/master/examples/hello/README.md Execute the main Go binary using Bazel. Ensure the Bazel build system is set up correctly for the project. ```bash bazel run //:hello ``` -------------------------------- ### List All Supported Platforms Source: https://github.com/bazel-contrib/rules_go/blob/master/docs/go/core/cross_compilation.md Query Bazel to list all available platforms defined in the Go toolchain. ```bash bazel query 'kind(platform, @io_bazel_rules_go//go/toolchain:all)' ``` -------------------------------- ### Download Go SDK with go_sdk.download Source: https://github.com/bazel-contrib/rules_go/blob/master/go/toolchains.rst Use `go_sdk.download` in MODULE.bazel to declare a Go SDK. This method is preferred for projects using Bzlmod. It allows specifying experiments. ```bzl # MODULE.bazel go_sdk.download( name = "go_sdk", version = "1.23.5", ) # select with bazel build --@io_bazel_rules_go//go/toolchain:sdk_name=go_sdk_with_rangefunc go_sdk.download( name = "go_sdk_with_rangefunc", version = "1.23.5", experiments = ["rangefunc"], ) ``` -------------------------------- ### Override Default Dependency Source: https://github.com/bazel-contrib/rules_go/blob/master/go/dependencies.rst Example of overriding the default 'com_github_golang_protobuf' dependency by declaring a custom http_archive rule before calling go_rules_dependencies. ```bzl load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") load("@bazel_tools//tools/build_defs/repo:git.bzl", "git_repository") http_archive( name = "io_bazel_rules_go", integrity = "sha256-M6zErg9wUC20uJPJ/B3Xqb+ZjCPn/yxFF3QdQEmpdvg=", urls = [ "https://mirror.bazel.build/github.com/bazelbuild/rules_go/releases/download/v0.48.0/rules_go-v0.48.0.zip", "https://github.com/bazelbuild/rules_go/releases/download/v0.48.0/rules_go-v0.48.0.zip", ], ) http_archive( name = "bazel_gazelle", integrity = "sha256-12v3pg/YsFBEQJDfooN6Tq+YKeEWVhjuNdzspcvfWNU=", urls = [ ``` -------------------------------- ### Add Go Dependency Source: https://github.com/bazel-contrib/rules_go/blob/master/docs/go/core/bzlmod.md Add a specific Go module dependency to your project using `bazel run @rules_go//go get`. ```sh bazel run @rules_go//go get golang.org/x/text@v0.3.2 ``` -------------------------------- ### Register Go SDK from go.mod file Source: https://github.com/bazel-contrib/rules_go/blob/master/docs/go/core/bzlmod.md Use the `go_sdk.from_file` extension to automatically download and register a Go SDK based on the version specified in your `go.mod` file. This is useful for ensuring consistent Go versions across builds. ```starlark go_sdk = use_extension("@rules_go//go:extensions.bzl", "go_sdk") # Download an SDK for the host OS & architecture as well as common remote execution # platforms, using the version given from the `go.mod` file. go_sdk.from_file(go_mod = "//:go.mod") ``` -------------------------------- ### Register Go SDK from go.work file Source: https://github.com/bazel-contrib/rules_go/blob/master/docs/go/core/bzlmod.md Alternatively, use `go_sdk.from_file` with the `go_work` attribute to register a Go SDK based on the version specified in your `go.work` file. This is an alternative to using `go.mod` for version management. ```starlark go_sdk = use_extension("@rules_go//go:extensions.bzl", "go_sdk") # Alternatively, use the version from a `go.work` file. go_sdk.from_file(go_work = "//:go.work") ``` -------------------------------- ### Add External Go Repositories Source: https://github.com/bazel-contrib/rules_go/blob/master/docs/go/core/workspace.md Add `go_repository` rules to your WORKSPACE file to manage external Go dependencies. This example shows how to download Go rules and Gazelle. ```starlark load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") # Download the Go rules. http_archive( name = "io_bazel_rules_go", integrity = "sha256-M6zErg9wUC20uJPJ/B3Xqb+ZjCPn/yxFF3QdQEmpdvg=", urls = [ "https://mirror.bazel.build/github.com/bazelbuild/rules_go/releases/download/v0.48.0/rules_go-v0.48.0.zip", "https://github.com/bazelbuild/rules_go/releases/download/v0.48.0/rules_go-v0.48.0.zip", ], ) # Download Gazelle. http_archive( name = "bazel_gazelle", integrity = "sha256-12v3pg/YsFBEQJDfooN6Tq+YKeEWVhjuNdzspcvfWNU=", urls = [ "https://mirror.bazel.build/github.com/bazelbuild/bazel-gazelle/releases/download/v0.37.0/bazel-gazelle-v0.37.0.tar.gz", "https://github.com/bazelbuild/bazel-gazelle/releases/download/v0.37.0/bazel-gazelle-v0.37.0.tar.gz", ], ) # Load macros and repository rules. load("@io_bazel_rules_go//go:deps.bzl", "go_register_toolchains", "go_rules_dependencies") load("@bazel_gazelle//:deps.bzl", "gazelle_dependencies", "go_repository") # Declare Go direct dependencies. go_repository( name = "org_golang_x_net", importpath = "golang.org/x/net", sum = "h1:7EYJ93RZ9vYSZAIb2x3lnuvqO5zneoD6IvWjuhfxjTs=", version = "v0.23.0", ) # Declare indirect dependencies and register toolchains. go_rules_dependencies() go_register_toolchains(version = "1.23.1") gazelle_dependencies() ``` -------------------------------- ### Internal go_test Example Source: https://github.com/bazel-contrib/rules_go/blob/master/docs/go/core/examples.md Configures an internal test for a Go library, embedding the library to access its internal interfaces. This is analogous to tests in the same package in the standard Go toolchain. ```bzl go_library( name = "lib", srcs = ["lib.go"], ) go_test( name = "lib_test", srcs = ["lib_test.go"], embed = [":lib"], ) ``` -------------------------------- ### Download Go SDK with go_download_sdk Source: https://github.com/bazel-contrib/rules_go/blob/master/go/toolchains.rst Use `go_download_sdk` in WORKSPACE to download a specific Go version. This is useful for setting up the Go toolchain for Bazel builds. ```bzl # WORKSPACE go_download_sdk( name = "go_sdk", version = "1.23.5", ) # select with bazel build --@io_bazel_rules_go//go/toolchain:sdk_name=go_sdk_with_rangefunc go_download_sdk( name = "go_sdk_with_rangefunc", version = "1.23.5", experiments = ["rangefunc"], ) ``` -------------------------------- ### Get Go Context Source: https://github.com/bazel-contrib/rules_go/blob/master/go/toolchains.rst Use this function at the top of custom Starlark rules to obtain a GoContext. This context is necessary for creating Go actions and interacting with Go providers. ```bzl def _my_rule_impl(ctx): go = go_context(ctx) ... ``` -------------------------------- ### Query Go Proto Library Rules Source: https://github.com/bazel-contrib/rules_go/blob/master/proto/core.rst These commands help you list `go_proto_library` rules for Well Known Types and Google APIs. ```bash bazel query 'kind(go_proto_library, @io_bazel_rules_go//proto/wkt:all)' ``` ```bash bazel query 'kind(go_proto_library, @go_googleapis//...)' ``` -------------------------------- ### Add Go Tool Dependency (Go 1.24+) Source: https://github.com/bazel-contrib/rules_go/blob/master/docs/go/core/bzlmod.md Use `bazel run @rules_go//go -- get -tool` to add a tool dependency. This modifies your `go.mod` file. ```sh bazel run @rules_go//go -- get -tool golang.org/x/tools/cmd/stringer ``` -------------------------------- ### External go_test Example Source: https://github.com/bazel-contrib/rules_go/blob/master/docs/go/core/examples.md Configures an external test for a Go library, depending on the library to only access its public interfaces. This is analogous to tests in a separate package in the standard Go toolchain. ```bzl go_library( name = "lib", srcs = ["lib.go"], ) go_test( name = "lib_xtest", srcs = ["lib_x_test.go"], deps = [":lib"], ) ``` -------------------------------- ### Load Go Build Rules Source: https://github.com/bazel-contrib/rules_go/blob/master/docs/go/core/workspace.md Load the necessary Go build rules at the top of your BUILD.bazel file. ```starlark load("@io_bazel_rules_go//go:def.bzl", "go_binary", "go_library", "go_test") ``` -------------------------------- ### Conditional Dependencies with `select` in `go_binary` Source: https://github.com/bazel-contrib/rules_go/blob/master/docs/go/core/platform-specific_dependencies.md Use Bazel's `select` function to conditionally include dependencies based on the target platform. This example shows how to add Linux-specific or Windows-specific dependencies to a `go_binary` target. ```bzl go_binary( name = "cmd", srcs = [ "foo_linux.go", "foo_windows.go", ], deps = [ # platform agnostic dependencies "//bar", ] + select({ # OS-specific dependencies "@io_bazel_rules_go//go/platform:linux": [ "//baz_linux", ], "@io_bazel_rules_go//go/platform:windows": [ "//quux_windows", ], "//conditions:default": [], }), ) ``` -------------------------------- ### Define a Go Binary Target Source: https://github.com/bazel-contrib/rules_go/blob/master/docs/go/core/workspace.md Add this to your root BUILD.bazel file to define a 'hello world' Go binary. This target compiles and links the specified Go source files into an executable. ```starlark load("@io_bazel_rules_go//go:def.bzl", "go_binary") go_binary( name = "hello", srcs = ["hello.go"], ) ``` -------------------------------- ### Building with Stamping and Status Script Source: https://github.com/bazel-contrib/rules_go/blob/master/docs/go/core/defines_and_stamping.md Command to build a Go binary with stamping enabled and a custom workspace status script. ```bash $ bazel build --stamp --workspace_status_command=./status.sh //:cmd ``` -------------------------------- ### Download Go SDK for a fixed OS/architecture Source: https://github.com/bazel-contrib/rules_go/blob/master/docs/go/core/bzlmod.md Use `go_sdk.download` with `goarch` and `goos` attributes to download a Go SDK for a specific operating system and architecture. This is essential for cross-compilation or building for specific remote execution environments. ```starlark go_sdk = use_extension("@rules_go//go:extensions.bzl", "go_sdk") # Alternatively, download an SDK for a fixed OS/architecture. go_sdk.download( version = "1.23.1", goarch = "amd64", goos = "linux", ) ``` -------------------------------- ### Register Go Toolchains and Dependencies Source: https://github.com/bazel-contrib/rules_go/blob/master/go/dependencies.rst Call `go_rules_dependencies`, `go_register_toolchains`, `gazelle_dependencies`, and `protobuf_deps` to set up the necessary Go toolchains and dependencies for your project. ```bzl go_rules_dependencies() go_register_toolchains() gazelle_dependencies() protobuf_deps() ``` -------------------------------- ### Configure gRPC and Related Dependencies Source: https://github.com/bazel-contrib/rules_go/blob/master/go/dependencies.rst Set up repository rules for gRPC and its associated Go libraries (x/net, x/text). Ensure build_file_proto_mode is set to 'disable' for the gRPC repository rule. ```bzl load("@bazel_gazelle//:deps.bzl", "gazelle_dependencies", "go_repository") gazelle_dependencies() go_repository( name = "org_golang_google_grpc", build_file_proto_mode = "disable", importpath = "google.golang.org/grpc", sum = "h1:J0UbZOIrCAl+fpTOf8YLs4dJo8L/owV4LYVtAXQoPkw=", version = "v1.22.0", ) go_repository( name = "org_golang_x_net", importpath = "golang.org/x/net", sum = "h1:oWX7TPOiFAMXLq8o0ikBYfCJVlRHBcsciT5bXOrH628=", version = "v0.0.0-20190311183353-d8887717615a", ) go_repository( name = "org_golang_x_text", importpath = "golang.org/x/text", sum = "h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg=", version = "v0.3.0", ) ``` -------------------------------- ### Build Pure Go Binaries Source: https://github.com/bazel-contrib/rules_go/blob/master/go/modes.rst Use the `--@io_bazel_rules_go//go/config:pure` flag to build pure Go binaries, avoiding CGO. Alternatively, set the `pure` attribute to `"on"` in a `go_binary` rule. ```bash bazel build --@io_bazel_rules_go//go/config:pure //:my_binary ``` ```bzl go_binary( name = "foo", srcs = ["foo.go"], pure = "on", ) ``` -------------------------------- ### go_binary Source: https://github.com/bazel-contrib/rules_go/blob/master/docs/go/core/rules.md Builds an executable from a set of Go source files in the `main` package. The binary can be run with `bazel run` or built and run directly. ```APIDOC ## go_binary
load("@rules_go//docs/go/core:rules.bzl", "go_binary")

go_binary(
    name,
    deps = [],
    srcs = [],
    data = [],
    out = "",
    basename = "",
    cdeps = [],
    cgo = False,
    clinkopts = [],
    copts = [],
    cppopts = [],
    cxxopts = [],
    embed = [],
    embedsrcs = [],
    env = [],
    gc_goopts = [],
    gc_linkopts = [],
    goarch = "",
    goos = "",
    gotags = [],
    importpath = "",
    linkmode = "",
    msan = False,
    pgoprofile = False,
    pure = False,
    race = False,
    static = False,
    x_defs = {},
)
### Description This rule builds an executable from a set of source files, which must all be in the `main` package. You can run the binary with `bazel run`, or you can build it with `bazel build` and run it directly. ***Note:*** `name` should be the same as the desired name of the generated binary. ### Attributes * **name** (Name) - Required - A unique name for this target. * **deps** (List of labels) - Optional - List of Go libraries this package imports directly. These may be `go_library` rules or compatible rules with the [GoInfo] provider. Default: `[]` * **srcs** (List of labels) - Optional - The list of Go source files that are compiled to create the package. Only `.go`, `.s`, and `.syso` files are permitted, unless the `cgo` attribute is set, in which case, `.c .cc .cpp .cxx .h .hh .hpp .hxx .inc .m .mm` files are also permitted. Files may be filtered at build time using Go [build constraints]. Default: `[]` * **data** (List of labels) - Optional - List of files needed by this rule at run-time. This may include data files needed or other programs that may be executed. The [bazel] package may be used to locate run files; they may appear in different places depending on the operating system and environment. See [data dependencies] for more information on data files. Default: `[]` * **out** (String) - Optional - Sets the output filename for the generated executable. When set, `go_binary` will write this file without mode-specific directory prefixes, without linkmode-specific prefixes like "lib", and without platform-specific suffixes like ".exe". Note that without a mode-specific directory prefix, the output file (but not its dependencies) will be invalidated in Bazel's cache when changing configurations. Default: `""` * **basename** (String) - Optional - The basename of this binary. The binary basename may also be platform-dependent: on Windows, we add an .exe extension. Default: `""` * **cdeps** (List of labels) - Optional - The list of other libraries that the c code depends on. This can be anything that would be allowed in [cc_library deps] Only valid if `cgo` = `True`. Default: `[]` * **cgo** (Boolean) - Optional - If `True`, the package may contain [cgo] code, and `srcs` may contain C, C++, Objective-C, and Objective-C++ files and non-Go assembly files. When cgo is enabled, these files will be compiled with the C/C++ toolchain and included in the package. Note that this attribute does not force cgo to be enabled. Cgo is enabled for non-cross-compiling builds when a C/C++ toolchain is configured. Default: `False` * **clinkopts** (List of strings) - Optional - List of flags to add to the C link command. Subject to ["Make variable"] substitution and [Bourne shell tokenization]. Only valid if `cgo` = `True`. Default: `[]` * **copts** (List of strings) - Optional - List of flags to add to the C compilation command. Subject to ["Make variable"] substitution and [Bourne shell tokenization]. Only valid if `cgo` = `True`. Default: `[]` * **cppopts** (List of strings) - Optional - List of flags to add to the C++ compilation command. Subject to ["Make variable"] substitution and [Bourne shell tokenization]. Only valid if `cgo` = `True`. * **cxxopts** (List of strings) - Optional - List of flags to add to the C++ link command. Subject to ["Make variable"] substitution and [Bourne shell tokenization]. Only valid if `cgo` = `True`. * **embed** (List of labels) - Optional - List of files to embed into the binary. Default: `[]` * **embedsrcs** (List of labels) - Optional - List of source files to embed into the binary. Default: `[]` * **env** (List of strings) - Optional - List of environment variables to set for the binary. Default: `[]` * **gc_goopts** (List of strings) - Optional - List of flags to pass to the Go compiler when building the binary. Default: `[]` * **gc_linkopts** (List of strings) - Optional - List of flags to pass to the Go linker when building the binary. Default: `[]` * **goarch** (String) - Optional - Target architecture for the Go build. Default: `""` * **goos** (String) - Optional - Target operating system for the Go build. Default: `""` * **gotags** (List of strings) - Optional - List of build tags to apply to the Go build. Default: `[]` * **importpath** (String) - Optional - The import path of the package. Default: `""` * **linkmode** (String) - Optional - The link mode to use for building the binary (e.g., `"internal"`, `"external"`). Default: `""` * **msan** (Boolean) - Optional - Enable MemorySanitizer. Default: `False` * **pgoprofile** (Boolean) - Optional - Enable pprof profiling. Default: `False` * **pure** (Boolean) - Optional - Build a pure Go binary (no C dependencies). Default: `False` * **race** (Boolean) - Optional - Enable race detector. Default: `False` * **static** (Boolean) - Optional - Build a static binary. Default: `False` * **x_defs** (Dict) - Optional - Dictionary of definitions for the Go preprocessor. Default: `{}` ``` -------------------------------- ### Create Go Binary with Proto Dependencies Source: https://github.com/bazel-contrib/rules_go/blob/master/proto/core.rst Builds a Go binary that depends on generated Go proto libraries. The `deps` attribute lists the `go_proto_library` targets. ```bzl load("@io_bazel_rules_go//go:def.bzl", "go_binary") go_binary( name = "main", srcs = ["main.go"], deps = ["//foo:foo_go_proto"], ) ``` -------------------------------- ### Launcher Script for MODULE.bazel Source: https://github.com/bazel-contrib/rules_go/wiki/Editor-setup Creates a launcher script for the Go packages driver when using MODULE.bazel to load rules_go. ```bash #!/usr/bin/env bash # See https://github.com/bazelbuild/rules_go/wiki/Editor-setup#3-editor-setup exec bazel run -- @rules_go//go/tools/gopackagesdriver "${@}" ``` -------------------------------- ### Fetch rules_go and Go Toolchain Source: https://github.com/bazel-contrib/rules_go/blob/master/docs/go/core/workspace.md Use this snippet in your WORKSPACE file to fetch the rules_go repository and register a supported Go toolchain. Ensure the version matches your project's requirements. ```starlark load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") http_archive( name = "io_bazel_rules_go", integrity = "sha256-M6zErg9wUC20uJPJ/B3Xqb+ZjCPn/yxFF3QdQEmpdvg=", urls = [ "https://mirror.bazel.build/github.com/bazelbuild/rules_go/releases/download/v0.48.0/rules_go-v0.48.0.zip", "https://github.com/bazelbuild/rules_go/releases/download/v0.48.0/rules_go-v0.48.0.zip", ], ) load(@io_bazel_rules_go//go:deps.bzl, "go_register_toolchains", "go_rules_dependencies") go_rules_dependencies() go_register_toolchains(version = "1.23.1") ``` -------------------------------- ### Register Custom SDK with go_wrap_sdk Source: https://github.com/bazel-contrib/rules_go/blob/master/go/toolchains.rst Integrate a Go SDK downloaded via a custom repository rule. The SDK must be named `go_sdk` for this to work. ```bzl # WORKSPACE load("@io_bazel_rules_go//go:deps.bzl", "go_rules_dependencies", "go_register_toolchains", "go_wrap_sdk") unknown_download_sdk( name = "go", ... ) go_wrap_sdk( name = "go_sdk", root_file = "@go//:README.md", ) go_rules_dependencies() go_register_toolchains() ``` -------------------------------- ### Querying Platform-Specific `config_setting` Rules Source: https://github.com/bazel-contrib/rules_go/blob/master/docs/go/core/platform-specific_dependencies.md This command lists all pre-declared `config_setting` rules provided by rules_go for various OS, architecture, and OS-architecture combinations. These are used as keys in Bazel's `select` expressions. ```bash bazel query 'kind(config_setting, @io_bazel_rules_go//go/platform:all)' ``` -------------------------------- ### Run Go Command with Bazel Source: https://github.com/bazel-contrib/rules_go/blob/master/README.rst Use this command to run the Bazel-configured Go SDK's 'go' binary. This ensures consistency with the Go version used by rules_go. ```bash bazel run @io_bazel_rules_go//go -- ``` -------------------------------- ### Test the Go Library with Bazel Source: https://github.com/bazel-contrib/rules_go/blob/master/examples/hello/README.md Run tests for the Go library using Bazel. This command verifies the correctness of the library code. ```bash bazel test //:hello_test ``` -------------------------------- ### Download a specific Go SDK version Source: https://github.com/bazel-contrib/rules_go/blob/master/docs/go/core/bzlmod.md Manually download and register a Go SDK for a specific version using `go_sdk.download`. This is useful when you need a precise Go version not necessarily dictated by your project's `go.mod` or `go.work` files. ```starlark go_sdk = use_extension("@rules_go//go:extensions.bzl", "go_sdk") # Download an SDK for the host OS & architecture as well as common remote execution # platforms, with a specific version. go_sdk.download(version = "1.23.1") ``` -------------------------------- ### Launcher Script for WORKSPACE Source: https://github.com/bazel-contrib/rules_go/blob/master/docs/editors.md Bash script to launch the gopackagesdriver using Bazel, for projects loading rules_go via WORKSPACE. ```bash #!/usr/bin/env bash exec bazel run -- @io_bazel_rules_go//go/tools/gopackagesdriver "${@}" ``` -------------------------------- ### Register Go Toolchains with Beta SDK Version Source: https://github.com/bazel-contrib/rules_go/blob/master/README.rst Use this snippet to register Go toolchains with a specific beta or release candidate version of the Go SDK. Ensure `go_rules_dependencies` is called first. ```bzl load("@io_bazel_rules_go//go:deps.bzl", "go_register_toolchains", "go_rules_dependencies") go_rules_dependencies() go_register_toolchains(version = "1.17beta1") ``` -------------------------------- ### Bzlmod Equivalent for Customizing Go SDK Source: https://github.com/bazel-contrib/rules_go/blob/master/go/toolchains.rst This snippet demonstrates the Bzlmod approach for downloading and customizing a Go SDK, including applying patches and enabling compiler source builds. ```bzl # MODULE.bazel go_sdk = use_extension("@io_bazel_rules_go//go:extensions.bzl", "go_sdk") go_sdk.download( name = "go_sdk", version = "1.23.5", patches = ["//:my_go_patch.diff"], patch_strip = 1, experimental_build_compiler_from_source = True, ) use_repo(go_sdk, "go_sdk") ```