Go:用于微服务和共享代码的存储库布局

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

Go: repository layout for microservices with shared code

问题

我们最近开始在新的微服务中使用Go语言。每个微服务都是一个Go模块,并且我们将它们作为一个单一代码库进行管理:

/
  services/
    s1/
      go.mod
      main.go
    s2/
      go.mod
      main.go

这个方式运行良好,但现在我们需要在s1s2之间共享一些代码 - 一些被两个服务使用的结构体,一个上传到S3的函数等等。

在这种情况下,应该如何正确地管理代码呢?理想情况下,我希望在代码库的根目录(services的同级目录)下有一个common目录,并将共享的代码放在那里 - 但是在编译s1s2时,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
│&#160;&#160; └── common.go
├── go.mod
└── services
    ├── s1
    │&#160;&#160; └── 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 &quot;This is a common function&quot;
}

Then in services/s1/main.go, you can import the common module:

package main

import (
        &quot;mymodule/common&quot;
        &quot;fmt&quot;
)

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.

huangapple
  • 本文由 发表于 2023年4月18日 20:23:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/76044567.html
匿名

发表评论

匿名网友

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

确定