Home > Software engineering >  Merge micro-services written in Go into one binary
Merge micro-services written in Go into one binary

Time:12-22

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?

CodePudding user response:

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.

CodePudding user response:

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

  • Related