Go: Project Structures
May 27, 2020Overview
Recently at work I was asked about structuring go projects, and it would seem that there are very few hard and fast rules on how to structure Go projects. So, I defined a small set of rules and this is now what we use amongst the team; they may not be perfect, but they certainly set a good standard that prevents a few headaches.
High Level Overview
- Your project folder has multiple packages in it
- Your project folder may have go files in it alongside other files like a readme, dockerfile, jenkinsfile, etc.
- Your project folder may contain a cmd folder which is where we will place all of our code for executables in here
- Each package can consist of one or more packages
Pacakge structure
- You may have a file named {package}.go which holds any constants and variables that are likely to be shared with subpackages in this directory. replace {package} with the name of your package
- It’s useful to specify any interfaces that sub packages will use in this package to help keep scope limited
- It’s useful to split error definitions out into their own file but not neccesarily essential
- Packages should never import a package at a lower depth than
themselves
- eg. Package a should never import anything from package b or c
- eg. Package b may import package a
- eg. Package c may import package a
- Packages may import a package at the same depth as themselves
- eg. Package b may import package c, and vice versa
- eg. Package a may import package d, and vice versa
- Packages may import other packages at a higher depth than themsleves
- eg. Package b may import package a
- eg. Package b may import package d
- eg. Package c may import package a
- eg. Package c may import package d
- When writing unit tests it’s useful to keep them in the same directory but files must be named something_test.go
- When writing integration tests it’s useful to create a new directory
under the existing one and create a new package named {package}_test
- This is useful for ensuring we only use the exported structures and values from {package}