There's no official structure to follow when you start coding in go. But there're common practices that can help organizing your code specially if it's not a simple project.
Here are some of the common patterns for organizing go app
pkg directory
Here you can put the packages that intended to be reused or imported by external users. As I mentioned it's not forcible to use pkg directory but if you do, you should make sure that packages inside it can be imported. As when people see it, they treat the code inside it as it can be imported.
internal directory
In this directory you can put all packages that can't be reused or imported by other users. Go compiler prevent importing code which is inside this directory, so yes it's a common pattern but supported by the compiler. So it may contain controllers, middlewares, configuration, etc.
cmd directory
In go, any file that belongs to main package
is an executable file. Which means that you have to pass all of these files when using go build file1.go file2.go main.go
or go run file1.go file2.go main.go
commands. So it its better to combine all of these files under a directory and use *
to refer to all executable files. Now you can build your app using go build cmd/*
or run go run cmd/*
.
scripts directory
Use scripts directory to do different build, analyzing, install operations or whatever tasks.
assets directory
Here you put static assets like images, media, etc.
docs directory
Here is the moment when your app is really going big so you want to specify a directory for documenting every component in your app
templates directory
HTML templates go here. Note that some directories can reside inside other directories. For example we can use template inside internal.
controllers or handlers directory
That's where you put the code logic for handling http requests. So you can make a file for each controller and this file contains functions, one for each endpoint. It's very common to use this directory if you're implementing Hexagonal architecture