How do I manage multiple binaries in a repo in Go?

Managing multiple binaries in a Go repository can be streamlined by organizing your code into packages and utilizing Go modules effectively. Here’s how you can structure your Go projects to handle multiple binaries efficiently:

Directory Structure

To manage multiple binaries, it's common to create a directory named `cmd` where each subdirectory represents a different binary. Here’s an example structure:

    .
    ├── cmd
    │   ├── app1
    │   │   └── main.go
    │   └── app2
    │       └── main.go
    ├── pkg
    │   └── somepackage
    │       └── somefile.go
    └── go.mod
    

Code Example for Each Binary

Here's an example of how each binary (in `app1` and `app2`) could look:

    // cmd/app1/main.go
    package main
    
    import "fmt"
    
    func main() {
        fmt.Println("Hello from app1!")
    }
    
    // cmd/app2/main.go
    package main
    
    import "fmt"
    
    func main() {
        fmt.Println("Hello from app2!")
    }
    

Building the Binaries

To build the binaries, you can navigate to the `cmd/app1` or `cmd/app2` directories and run:

    go build -o app1
    go build -o app2
    

Alternatively, you can use the command:

    go build ./cmd/app1
    go build ./cmd/app2
    

Managing Go binaries Go modules multiple binaries in Go