I am sure, how to structure a Go Project, would have been most obvious question which everybody have thought through and it is very obvious. Specially after we write some basic hello world which has only main.go or after doing workouts in Go Playground
As we step up and write more code which involve various layering, then it becomes very essential to organize the code, so that:-
- easy to understand and maintain
- each package purpose becomes self explanatory by it’s name
- reduce interdependencies in the code
- increase code reusability
- ease of collaboration
Well, you can think of more points, but the fact is, it is very important to follow a basic template which is set a as standard by various GO projects ( GO doesn’t provide any official docs on project structure as such) and later on top of that, one can evolve their own structure as needed.
This is what, I have followed so far for my basic applications in GO. I have not hit that complexity so far, as I have just started learning and writing basic applications in GO.
/cmd/app/«your app name»
So, on the root of your project, you will have cmd/app/«your app name»
for example If you are building product API, then could you below
This folder, will always have only one file, and that’s your starting point of project -
As the name suggest, all files and sub folders inside internal, will be private your your application and will not be shared externally.
for example - you can further define sub-folders like data and handlers
internal is official: it’s the only directory named in Go’s documentation and has special compiler treatment
🔔 The other important point to note here is - in GO, you can have files with exact same name as long as they are in different package.
Also, in GO, it is NOT a good practice to use naming like ProductHandlers.go. As the product.go file is defined in the handler package, it is implicit that it is handler. ⭐
You will have go files here, which are ok to be used by external applications. Other project will use these files from pkg.
Mostly your public API code goes here in the pkg
You could have static folder which contains static files used by your project.
If files are internal to your app, then you can very well move this static folder inside internal.
You could have a look at very basic project structure which I have used in my repo in Go REST using Gorilla Mux
I would also recommend to have a look at GO standard project layout