Import Existing Go Application into the Bazel Monorepo

in my previous post, i already post about how to setup new go application into bazel monorepo. you can check my previous post here .

Alright, we’’ll get to the point by setting up the Go application that is already running into the bazel monorepo

1. copy the existing project into the monorepo folder. assuming we will name it `go-existing` and save it in the `packages` folder

2. create BUILD.bazel file in the go application root folder:

load("@bazel_gazelle//:def.bzl", "gazelle")

in the BUILD.bazel file. the first line is to call the gazelle library. the second line is the path and import path that will be used for the go application. This will affect the dependent library in the application to be able to call packages in the GO application. third line to define naming in gazelle. the fourth line is to call the bazel library for go rules. and the last line is go_binary, it contain the first attribute is the name of the go application which will be called and bazel will look for it from the name defined in go_binary. the second attribute is to embed or call the go library. the last is the visibility attribute on a rule controls whether the rule can be used by other packages. Rules are always visible to other rules declared in the same package.

3. move or copy go.mod to the root of the monorepo bazel folder.

4. WORKSPACE update

update workspace file by running the command:

$ bazel run //:gazelle --update-repos -from_file=go.mod

You can run the same command in the future to update existing WORKSPACE file in root folder to include new go library from you go.mod

5. update dependency in build file

update BUILD.bazel file by running the command:

$ bazel run //:gazelle

this will create or update all of BUILD.bazel file in your bazel directory based on import package in your source code. so you dont have the effort to create or update BUILD.bazel file in your monorepo, and let gazelle do the hardwork.

6. Build or Run the applications

build go-existing application:

$ bazel run //packages/go-existing:hello-world

if you want to build application into the binary file run this command :

$ bazel build //packages/go-existing:hello-world

bazel will show you where the binary target file is.
in this example and build in mac os X, binary file located in :

bazel-bin/packages/go-existing/darwin_amd64_stripped/hello-world

run binary file :

$ ./bazel-bin/packages/go-existing/darwin_amd64_stripped/hello-world

Software Developer, Daily Indonesian Gopher.