Go Multi Module Dependency Management

Issue

I am new to goLang. I am tring to develop a multiModule project. my workspace folder is
like

root
   1-Authz
   1.1-Main.go
   1.2-go.mod (contains:module com.mbt.authz)
   1.3-go.sum
   2-Product
   2.1-Main.go
   2.2-go.mod  (contains:module com.mbt.product)
   2.3-go.sum
   3-go.work
   4-GoMultiModule.code-workspace

   go.work folder is like 
   go 1.18

   use(
    ./Authz
    ./Product
   )

Both modules can run by itself. But I want to define a method in Authz and call that
function from Product. What should I do, how can I add dependency to Product module from my local workspace?

Solution

This is a FAQ for many new golang developer.

In golang, Module and Package are not the same thing. A module may contains one or more packages. Module is initialized with go mod init [modulename] command. This command will create a go.mod file. Package can be simply defined in code with package [packagename]. Package in the same module (let’s call it local package) can be import with import "[packagename] [modulename]/[pathofpackage]"

In your case, if you don’t want to create different module, you can delete the go.mod and go.sum file in both Authz and Products folder. Then in Root folder, run go mod init root. Then import auth package in product code with something like import (authz "root/authz") (authz is the package name delcared in Authz’s code)

If authz has to be a different module, it will be treated as a different module which cannot be import diretly like a local package.

To import a local module in Authz folder, you need to edit the go.mod file in products folder like this:

module somemodulename

go 1.16

require (
    authzmodulename v0.0.0
)

replace authzmodulename v0.0.0 => ../Authz/

Answered By – Cyril Zhou

Answer Checked By – Timothy Miller (GoLangFix Admin)

Leave a Reply

Your email address will not be published.