英文:
Go: repository layout for microservices with shared code
问题
我们最近开始在新的微服务中使用Go语言。每个微服务都是一个Go模块,并且我们将它们作为一个单一代码库进行管理:
/
services/
s1/
go.mod
main.go
s2/
go.mod
main.go
这个方式运行良好,但现在我们需要在s1
和s2
之间共享一些代码 - 一些被两个服务使用的结构体,一个上传到S3的函数等等。
在这种情况下,应该如何正确地管理代码呢?理想情况下,我希望在代码库的根目录(services
的同级目录)下有一个common
目录,并将共享的代码放在那里 - 但是在编译s1
和s2
时,Go语言如何从那里获取代码呢?
英文:
We recently started using Go for new microservices. Each microservice is a Go module, and we manage them as a monorepo:
/
services/
s1/
go.mod
main.go
s2/
go.mod
main.go
This works fine, but now we need to share some code between s1
and s2
- some structs used by both services, a function that uploads to S3, etc.
What's the correct way of managing this situation? Ideally, I'd have a common
directory at the repo root (sibling of services
) and put the common code there - but how will Go take the code from there when compiling s1
and s2
?
答案1
得分: 4
我认为你所问的实际上只是一个变体,参考链接是关于如何组织Go应用程序以生成多个可执行文件的。你需要将go.mod
文件移动到顶级目录并进行重命名,以便你的目录结构如下:
.
├── common
│ └── common.go
├── go.mod
└── services
├── s1
│ └── main.go
└── s2
└── main.go
go.mod
文件的内容应该类似于:
module mymodule
如果common/common.go
的内容如下:
package common
func CommonFunction() string {
return "This is a common function"
}
那么在s1/main.go
中,你可以导入common
模块:
package main
import (
"mymodule/common"
"fmt"
)
func main() {
res := common.CommonFunction()
fmt.Println(res)
}
你可以像这样构建s1
服务:
go build ./services/s1
构建s2
服务的方式类似:
go build ./services/s2
通常,你会在顶级目录下使用一个Makefile
来自动化构建多个服务。
英文:
I think what you're asking is really just a variation of "<https://stackoverflow.com/questions/50904560/how-to-structure-go-application-to-produce-multiple-binaries>".
You would move your go.mod
to the top-level directory rename, so that you have this layout:
.
├── common
│   └── common.go
├── go.mod
└── services
├── s1
│   └── main.go
└── s2
└── main.go
And a go.mod
that starts with something like:
module mymodule
If common/common.go
looks like this:
package common
func CommonFunction() string {
return "This is a common function"
}
Then in services/s1/main.go
, you can import the common
module:
package main
import (
"mymodule/common"
"fmt"
)
func main() {
res := common.CommonFunction()
fmt.Println(res)
}
And you would build the s1
service like this:
go build ./services/s1
Building s2
would be similar:
go build ./services/s2
You would typically have a top-level Makefile
to automate building of the multiple services.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论