Go Workspaces: Simplifying Multi-Modular Projects

Sabbir Ahmed
3 min readJun 17, 2023

--

A multi-modular Go workspace provides a structured and efficient approach to managing multiple independent microservices or apps within a single workspace. It enables code isolation, simplified dependency management, code reusability, and collaboration while maintaining efficient build and test processes.

Background image by rawpixel.com on Freepik

Let’s understand when we type go mod init example/module in any Unix-based terminal —

When we create a go module outside of GOPATH, go mod initcommand populates a GOMOD environment variable and creates a go.modfile in the current directory. This allows for more flexibility and independence in a single microservice or a monolithic development stage. But the problem happens when we want to use a monorepo in our project. I want to emphasize — “monorepo is not a monolith”. Sorry, a slight deviation. Okay, so we want to use monorepo in our project. For example, we want to build 3 modules named — module1, module2, module3. Let’s create 3 directories under our project -

├── module1
├── module2
└── module3

when we run go mod github.com/by-sabbir/go-workspace-example/module1g immediately vscode complains that the library is not in the workspace module

Limitations in go mod init

We already know that Google is big on monorepo. So, they must’ve something planned for the golang too. But not until go version 1.18! For go 1.18 and later they introduced workspace. The management commands will be found at go work subcommand.

To create a workspace we need to run go work init command. This adds a new environment variable GOWORK in the current directory and GOMOD becomes null. Also, it will add another file go.work with the current go version.

Now, we can initialize any module without any issues. To add the module to our workspace, we just need to run the following command — for our example, we need to add module1 into our workspace —

go work use ./module1

Let’s pull the example repo and play around —

https://github.com/by-sabbir/go-workspace-example

If we run each module we will have the following outputs —

output

This is how Go provides the easiest way to manage and maintain multi-modular projects with Go Workspace.

--

--