I have searched for a solution for organizing Go files in a project and found this post. I wonder what the role of the cmd
folder is, that was used in the 2nd section of that post. Is it a magic word for the Go compiler? On the other hand I was reading the Go documentation and there is nothing about a cmd
folder in there.
So what about this folder? And what is the best practice for structuring project files in Go that support source files, projects binaries, 3rd party packages and unit tests.
The author of the post you cite explicitly says the Camlistore application introduced him to the cmd convention.
If you look at the source code to Camlistore you will notice that project uses a custom system for building, namely "make.go".
cmd is special only because the Camlistore project uses "go run make.go" to build and make.go is aware of how to build targets in the cmd directory. Or in the more general case, cmd is special only if you use a build system that treats it as special.
The post has already made it clear, to summarise:
- It's not a magic nor standard in Go. It's just a convention.
- You can have multiple binaries when putting them into a sub-folder which is not possible in the root folder.
- By making you taking your binary as a client instead of a host or portal of your application, it can drives you to the so-called 'library-driven-development' way of architecting your program. This separation 'helps you make a cleaner abstraction' and more common of you code logic.
I'm not sure about the best practice. The official documents have many hints about the project files structuring. On my personal practice, besides the cmd
folder for the binaries, I
1. Group source files into packages(sub-folders) inside the src
folder,
2. Copy 3rd party packages to the vendor folder;
3. Place unit tests files side by side with its target source file.
These links may be helpful:
Organizing Go code
The Go Blog: Organizing Go code
The Go Blog: Package names
golang-standards/project-layout