How do you write a package with multiple binaries in it?
If you don't want to install the binaries into $GOPATH/bin
, you could do what other open source projects do, which is create a script.
Most of the projects out there have make files and build scripts for producing multiple binaries.
In your case, you could build a script that iterates over the packages in cmd
, and run go build
on each.
cd $GOPATH/someProject
for CMD in `ls cmd`; do
go build ./cmd/$CMD
done
This results in:
[root@node1 test]# ls $GOPATH/someProject
bin1 bin2 cmd
Couple of trending projects that you can look at:
- Grafana - https://github.com/grafana/grafana/blob/master/build.go
- Torus - https://github.com/coreos/torus/blob/master/Makefile
- Caddy - https://github.com/mholt/caddy/blob/master/dist/automate.go
The command:
go install ./...
should build all binaries under your current directory (i.e. ./...
) and put them on $GOPATH/bin
.
From the go build
help:
When compiling multiple packages or a single non-main package, build compiles the packages but discards the resulting object, serving only as a check that the packages can be built.
In order to build all packages under a directory, you can run go install ./...
. All of your packages will be built and installed (i.e. put under $GOPATH/bin).
With your example, you'd have two executables produced: $GOPATH/bin/bin1
and $GOPATH/bin/bin2
There is also the alternative of writing a simple Makefile to do what you want.