Search code examples
gogo-modulesgo-packages

Issue with developing a multi-module Go workspace


My folder structure looks something like this... (say my git repo name is demorepo)

demorepo
|--directory1
   |-- (no go.mod at this level)
   |--module1
      |--package1 --------->--------------->--------------------->----|
      |--go.mod (github.com/demorepo/directory1/module1)              |
      |--go.sum                                                       |
   |--module2                                                         |
   |--module3                                                         |
|--directory2                                                         |
  |-- (no go.mod at this level)                                       |
  |--newmodule ------<------------<------------------<----------------|

Now, I want to use a function defined in "package1" in my "newmodule"

When I hit go get <repo_address>/directort1/module1/package1 at "new_module" it says ....

github.com/<repo>@upgrade found (v0.0.0-20211215055943-92e412ad4a12), but does not contain package github.com/<repo>/directory1/module1/package1

Solution

  • There is a proposal for a Go Workspace File for Go 1.18 which should simplify this task.

    Meanwhile, you can use the replace directive in your go.mod file to refer to a module located on a local filesystem.

    demorepo/directory1/module1/go.mod:

    module github.com/<repo>/directory1/module1
    

    demorepo/directory2/newmodule/go.mod:

    module github.com/<repo>/directory2/newmodule
    
    replace github.com/<repo>/directory1/module1 => ../../directory1/module1
    

    Now you can import github.com/<repo>/directory1/module1/package1 in newmodule normally and it'll refer to the local module1.

    You might not want the replace directive in the go.mod file itself, and instead make a copy of it e.g. go.local.mod and use it when building your project: go build -modfile go.local.mod . (can also add go.local.mod to .gitignore).