Ayush Gupta
Ayush Gupta

Reputation: 9305

How to nest one go module inside multiple Go modules as local dependency

$ go version
1.13.3

I have a folder structure as follows:

GOPATH
+---src
     +--- my-api-server
           +--- my-auth-server
                 +--- main.go
                 +--- go.mod
                 +--- go.sum
           +--- my-utils
                 +--- go.mod
                 +--- go.sum
                 +--- uuid
                       +--- uuid.go

my-auth-server uses my-api-server/my-utils/uuid as a dependency

I tried moving my-utils inside my-auth-server, but as a library, my-utils will be used in multiple places.

Now, my-utils also has a go.mod, but that contains a module declaration. If I place it in my-auth-server, the module path becomes my-api-server/my-auth-server/my-utils

If I have 2 servers,

I cannot place my-utils inside both because there can only be one module declaration per go.mod.

So, how I use this in two different projects as submodule?

Any help in solving this would also be appreciated.

Upvotes: 1

Views: 748

Answers (1)

jazz
jazz

Reputation: 509

A clean way to do achieve this is to have utils a standalone module outside of all projects and then import wherever you want. Since its evident you want it to be a module itself.

Like

GOPATH
+---src
     +--- my-api-server
           +--- my-auth-server
                 +--- main.go
                 +--- go.mod
                 +--- go.sum
     +--- my-utils
          +--- go.mod
          +--- go.sum
          +--- uuid
               +--- uuid.go

But if you still need to have utils also maintained as part of your API server then have your API server as module and import it wherever you need utils package. This is discouraged but will not do any harm since GO optimizes as part of compilation required context.

Like this

GOPATH
+---src
     +--- my-api-server
           +--- my-auth-server
                 +--- main.go
                 +--- go.mod
                 +--- go.sum
                 +--- my-utils
                      +--- uuid
                           +--- uuid.go

What i understand is you need to maintain multi modules in single repo and cross refer. As far as I understand this is not how its supposed to work since you can always cross refer nested package by module relative path.

Also maybe you know this, but since you are using modules, you need to sit in GOPATH/GOROOT for resolution.

Upvotes: 2

Related Questions