How to import a local package from different directory in Go Modules?

huangapple go评论90阅读模式
英文:

How to import a local package from different directory in Go Modules?

问题

我有一个包含6个微服务的项目。每个微服务都在自己的目录中,并且它们都是Go模块,例如:

  • user-ms
  • project-ms
  • messages-ms

所有微服务中都有一些重复的代码,例如mongo方法、一些配置和一些结构体等。我想将所有重复的代码合并到一个包中,然后愿意在我们的微服务中导入这个包。由于公司的限制,我无法在Github上创建一个仓库。

如果我在$GOPATH/src/中创建一个文件夹,我不知道如何在docker-compose.yml中包含它。

是否可以创建一个文件夹("common-utils"),然后在其他模块中导入它?

  • user-ms
    -- go.mod
  • project-ms
    -- go.mod
  • messages-ms
    -- go.mod
  • common-utils
    -- go.mod
英文:

I have a project which includes 6 microservices. Every microservices are in its own directory and they are Go modules, like:

- user-ms
- project-ms
- messages-ms

There are some duplicated codes in all microservices, like mongo methods, some configs, and some structs etc. I want to merge all the duplicated codes into a package. Then, I am willing to import the package on our microservices. Creating a repository on Github is impossible for me due to company restrictions.

If I create a folder in $GOPATH/src/, I don't know how to include it on docker-compose.yml.

Is it possible to create a folder ("common-utils") then import on the other modules?

- user-ms
-- go.mod
- project-ms
-- go.mod
- messages-ms
-- go.mod
- common-utils
-- go.mod

答案1

得分: 1

你可以使用本地包替换你的包名。

go mod edit -replace github.com/remote_package=../local_package

go mod tidy
英文:

You can replace your package name with local package.

go mod edit -replace github.com/remote_package=../local_package

go mod tidy

huangapple
  • 本文由 发表于 2021年8月7日 20:17:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/68692302.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定