Wei Huang
Wei Huang

Reputation: 728

Merge micro-services written in Go into one binary

my app consists of several golang written programs that run inside docker/k8s micro-services arch. Now, we want it to run directly on Linux without docker/k8s. So we’re thinking to merge all the programs into a single binary program. Which would be best way since each program is organized in cmd/main.go, internal/{aaa,bbb,ccc}/xxx.go? Thanks!

What I can think of now is to re-organize each service in pkg/.../xxx.go, including all current code in main.go. Then my all-in-one.go will import all the main.go code.

Any suggestions?

Edit:

Update reason for merging. 1) the target platform is embedded system, I'd like to make the app as small as possible, and as easier to deploy as possible. 2) I'd also like to try use the all-in-one app in system test, as it's more light-weight to run locally on developer machine than the real micro-service k8s version.

Upvotes: 0

Views: 420

Answers (2)

Adrian
Adrian

Reputation: 46602

Which would be best way since each program is organized in cmd/main.go, internal/{aaa,bbb,ccc}/xxx.go?

You'll have to reorganize them. Most Go projects that aren't tiny/disposable follow some version of the following:

  • One or more main packages under cmd/commandname for each buildable command, with very little code inside: generally just a main() entrypoint function that does nothing but call code from some other package(s).
  • All models and application logic in other packages outside cmd, where it can be shared by multiple commands (or other projects) as needed, and easily unit-tested.

That said, I'd suggest looking carefully at whether it's really necessary or helpful to merge these rather than just running the services side by side as they are. Even so, it sounds like reorganizing the projects could be beneficial either way.

Upvotes: 1

Nick
Nick

Reputation: 116

I think the best way is to start a new project and copy/paste code into new functions and packages. If you have multiple functions with the same name (func main()) or the same file name (main.go) your code won't compile.

I would start of with a brand new main.go and start to implement the code in subfolders f.e. project1/project1.go

Package can be imported then via import yourpackageurl.com/project1 into the main.go

Upvotes: -1

Related Questions