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.
/cmd. This folder contains the main application entry point files for the project, with the directory name matching the name for the binary.
A better way to organize a Go project is to put relevant Go code files into a subdirectory under the main directory for the project so that other parts of the project are able to find the APIs and use them. Keeping all source files under the same directory is not a very good idea, even though you can do it.
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
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