Golang with bazel: Part-1 Setup
Bazel is a build tool that is recently gaining popularity over other build tools such as Makefiles.
Advantages of bazel:
- It supports multiple languages including c++, golang, java, python and many others.
- Incremental builds and unit test runs are blazing fast. It caches the result of last unit test run and executes only tests which are affected by the incremental code changes.
- Due to support for multiple languages and fast builds, it is perfect for monorepo codebase.
Let’s take a look at example codebase that uses golang with bazel. In the above example, there are 3 types of file types present. These are .go, WORKSPACE and BUILD.bazel.
WORKSPACE: This file identifies the directory and its contents as a Bazel workspace.
BUILD.bazel: It tells bazel how to build different parts of the project. Every package will have its own BUILD.bazel file. We can automatically generate BUILD.bazel file (excluding root BUILD.bazel) using gazelle tool. Gazelle is a build file generator for Bazel projects.
In this tutorial, we will write a hello world go program and build it with bazel. This tutorial will require installation of bazel and gazelle tool. There are 4 files that are required for bazel build with golang to work. Let’s add these one by one.
Workspace file: It provide rules to download io_bazel_rules_go & bazel_gazelle, registers go toolchain and sets up gazelle dependencies.
Root BUILD.bazel file contents
Add below go file in hello-world/main.go path
Package level BUILD.bazel can be automatically generated using gazelle tool. Run the below command from root directory of the project. After running this command, BUILD.bazel file will be automatically created in hello-world directory.
bazel run //:gazelle
Now, it is time to run the go program via bazel. The below command runs hello-world rule defined in BUILD.bazel file inside hello-world directory. It should print “Hello world” in the console.
bazel run //hello-world:hello-world
Link for the source code: https://github.com/shubhag/bazel-golang-hello-world/tree/hello-world