Create Go Monorepo with Go-modules and Bazel

Bazel
  1. Go Modules — we wanna use go mod for managing dependencies
  2. Shared codebase — we wanna reuse our code in different application
  3. Test — we wanna run tests on single/all applications
  4. Build — we wanna build every application separately

1. Init go modules

We need to create go mod in our folder:

2. Create for example two application

Let’s create a folder packages that folder will have all our applications.

mkdir packages
cd packages
mkdir main_app
mkdir second_app
cd main_app && touch main.go && cd ../
cd second_app && touch main.go && cd ../
mkdir shared && touch shared.go - that file for shared code

3. Create a workspace for our monorepo

In the root folder, we need to create WORKSPACE file with content:

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

4. Create a build for applications

Every application in the application folder should have BUILD like an entry point for Bazel

Application BUILD file
  1. go_binary
  2. go_test

Section go_binary

This section has some field full list you can find in the link. I will just describe some of them:

Section go_test

“name” — for the run test

Let's add some shared content

For creating an application like real life I add a router in both applications with similar content

Router in main_app
Build file for Router in main_app

Section go_library

“name” — the name for Bazel, for use in dep

5. Create a shared folder and build

In the previous step, we have a reference on a shared folder.

Health handler
Health handler build

6. Let's build and test our applications

For build main application we can use the command:

bazel build //packages/main_app:main_app
bazel build //packages/second_app:second_app

Test

Single application test:

bazel test //packages/second_app/...:all
bazel test //packages/...:all

Dep graph

Bazel can create dep graph with the command:

bazel query 'allpaths(packages/...,//packages/shared/handlers/health:health)' --output graph | dot -Tpng > dep.png

7. Enjoy!

In this example, I showed the basis for creating a monorepo in Go, if you are interested, I will continue the article and tell how to use for example protobuf or general static files in monorepo.

--

--

Software engineer

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store