A while back (2020), I published an article on How to Structure a Go Command-Line Project. Within that article, I stated that while there are many recommendations on structuring Go Projects, there is no set standard.
The lack of a standard causes many new Gophers to question the best way to structure a project, A question I still see to this today.
This article will share how I structure Go Projects for backend services, similar but slightly different from how I structure Command-Line Projects.
While this article reiterates some positions, I first recommend reading the original Command-Line Projects article to understand my structure’s reasoning and decisions.
Where does main.go go?
For command-line applications, my original article suggested placing the
main.go file in the top-level directory of the repository. This recommendation made installing the project easier with
go get). But that recommendation is less useful for a backend service style project.
It’s not very common for users of a backend service to install anything locally, so for this use case, I tend to follow the common practice of placing the
main.go inside of a
Specifically, for an application named
myapp, I would create the
Suppose this project will produce both a server-side application and a command-line application. Then I tend to create two directories within
cmd/, the first being
myapp-server, which contains the startup logic for the server-side application. And the second is
myapp, which includes the startup logic for the client-side command-line application.
Keep main.go small and simple.
My original article explained the benefits of keeping
main.go trim, with only enough code to start the service.
For backend services, this is still very true. If we look at an example I’ve created below, I only start a very basic logger and load my application config.