0

After viewing the go tool source code, along with reading this SO answer (and the linked article): What is a sensible way to layout a Go project (Separate your binary from your application)

E.g. the following setup:

myapp/
  cmd/
    first/
      main.go
    second/
      main.go
    third/
      main.go
  otherpackage/

I am curious as to how you would go about implementing/building/debugging such a solution?

Am I supposed to have a main.go in the root which then somehow executes the different packages in the cmd directory depending on which command the user runs? Or how do I build this multi-command package without a 'main' package in root?

Community
  • 1
  • 1
fgblomqvist
  • 2,244
  • 2
  • 32
  • 44
  • This existing question may provide you with some clues (http://stackoverflow.com/questions/22391847/package-structure-for-go-app-engine-project) – miltonb May 23 '16 at 04:55

1 Answers1

1

You do not need a main.go in the root package. If you are into the myapp folder and run go install ./... then Go will recursively search for main() functions in subfolders.

For each main() function in a different package, Go will compile it in a single executable containing all the necessary packages. In your example, it would produce three binaries: first, second and third

About the implementation/debugging you just do it the usual way. That is, you implement and test your packages one by one with standard tests. If you want to test the compiled binaries, you can use the exec.Cmd struct.

Also, if you want good-looking commands, you can use some third-party libraries like cobra or cli

T. Claverie
  • 11,380
  • 1
  • 17
  • 28
  • Thank you! Digging deeper into the go tool code, I also noticed that the binary "go tool" actually looks for and executes other binaries. Executing "go tool vet" will actually execute a binary named just "vet". Using this way, they can build all their commands like separate binaries, but still give you the feeling that it's just one big well-organized one. – fgblomqvist May 23 '16 at 08:06