Home >Backend Development >Golang >Go: Repository layout for microservices with shared code

Go: Repository layout for microservices with shared code

王林
王林forward
2024-02-09 09:33:28849browse

Go: Repository layout for microservices with shared code

Go is a powerful programming language that has become increasingly popular in microservice architectures in recent years. Its simplicity, efficiency, and concurrency make it ideal for building high-performance applications. When building microservices with Go, the layout of the repository is an important consideration. In this article, PHP Editor Banana will introduce a microservice repository layout with shared code to help you better organize and manage your code.

Question content

We recently started using go to develop new microservices. Each microservice is a go module and we manage them as a single repository:

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

This is working fine, but now we need to share some code between s1 and s2 - some structures used by both services, functions uploaded to s3, etc.

What is the correct way to handle this situation? Ideally, I would have a common directory in the repository root (sibling of services) and put the common code there - but when compiling s1# How will go get the code from there when ## and s2?

Workaround

I think what you're asking is really just "

How to build a go application to generate multiple binaries?".

You can move

go.mod to the top level directory and rename it so that you have the following layout:

.
├── common
│   └── common.go
├── go.mod
└── services
    ├── s1
    │   └── main.go
    └── s2
        └── main.go

There is also a

go.mod which starts 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)
}

You would build the

s1 service like this:

go build ./services/s1

Build

s2 Similar to:

go build ./services/s2

You will typically have a top-level

makefile to automatically build multiple services.

The above is the detailed content of Go: Repository layout for microservices with shared code. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete