How to setup project structure to produce library and cli with same name in single repository?
Suppose my project name is project
. I want to make it importable with name
project
and have executable binary with name project
when installed with
go get
. My setup currently is like this:
host.com/project/
project/
main.go
core/
project.go
Then, when installed with:
go get host.com/project/project
it installs project
as executable which pulls core
as dependency. In
core/project.go
file, the package has this:
package project
The problem is it is imported with:
import (
"host.com/project/core"
)
And it exports project
as name space not core
which violates go's convention.
How can I do this?
This isn't a convention, and you may do however you like, but it's a common practice to have a cmd
folder in the project root, and all the executables go under that, each in is own folder.
So a good solution in your case could be simply:
host.com/project/
cmd/
project/
project.go
filea.go
fileb.go
In filea.go
and fileb.go
the package declaration should be:
package project
In cmd/project/project.go
package and import declaration should be:
package main
import "host.com/project"
Of course if your project is more complex, you may create further packages under the project root, and it may have multiple commands (multiple main
packages), e.g.:
host.com/project/
cmd/
project/
project.go
prjtool/
prjtool.go
packagex/
x.go
packagey/
y.go
filea.go
fileb.go
An example following this layout is the very popular Go Delve debugger (4.5k stars currently), available at https://github.com/derekparker/delve.
A very complex repository example is the golang.org/x/tools
package which is a collection of multiple, essential Go tools, available at https://github.com/golang/tools/. Its cmd
folder contains more than 20 subfolders (commands), many of the tools (main
packages) even consist of multiple .go
files (but each using package main
declaration, forming a single package of the executable).
Also check out the following related question: What is a sensible way to layout a Go project
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With