Introduction
Go 1.18 introduced workspace which makes life easy with multi-module development spaces. Here’s a sneak peak on how to use it and set up the develoment environment on Goland. Each module has it’s own go.mod
and all the dependencies can be synced in one shot throughout the project.
What’s a Golang Workspace?
Workspaces in Go 1.18 let you work on multiple modules simultaneously without having to edit go.mod files for each module. Each module within a workspace is treated as a main module when resolving dependencies.
Previously, to add a feature to one module and use it in another module, you needed to either publish the changes to the first module, or edit the go.mod file of the dependent module with a replace directive for your local, unpublished module changes. In order to publish without errors, you had to remove the replace directive from the dependent module’s go.mod file after you published the local changes to the first module.
With Go workspaces, you control all your dependencies using a go.work file in the root of your workspace directory. The go.work file has use and replace directives that override the individual go.mod files, so there is no need to edit each go.mod file individually. source
Defining Modules
Create two sub directories within your project, for e.g., module-1
and module-2
.
Initialize a go project within the directories using go mod init
. From now, let’s call these directories as modules.
Here’s how the directory tree going to look like.
➜ workspace-playground tree
.
├── go.mod
├── main.go
├── module-1
│ └── go.mod
└── module-2
└── go.mod
2 directories, 4 files
➜ workspace-playground
We haven’t talked about main.go
yet. It can be used as usual. There’s no hook to workspace during project startup.
Wiring Modules to Project
Now it’s time to wire the two modules to the main project. To achieve that, we’ll create a go.work
file.
go 1.18
use (
.
./module-1
./module-2
)
Doing the above will wire the project with the modules.
Goland Setup
-
To use Intellij Goland with workspace, auto modules resolution etc, you need to enable Go Modules Integration in the preferences. Go to Preferences > Go > Go Modules > Enable Go Modules Integration.
-
Update GOROOT to use Go Version > 1.18.