Creating the Directory Structure

In this lesson, you will learn about some best practices that emerged in the Go community when building large-scale programs. Then, you'll select a directory structure for multi-git.

Common directory structures for Go programs

We identified common elements of a Go program, but, how do we go about organizing them in a directory structure? We will discuss several common approaches.

Flat single directory

The flat single directory approach has no internal structure. All the files live in the project’s root directory. This is the approach used by multi-git 0.1, and it is appropriate for very small programs.

The minimal approach

The minimal approach advocates just two top-level directories: cmd for executables and pkg for libraries. For each command and package, there will be a sub-directory under the respective cmd and pkg directories. Every other file that belongs to a specific command or package will live in their sub-directory. Project-level files live in the project’s root directory.

The main benefit of this approach is its simplicity. The top-level structure of the project is very clear. The downside of this approach is that it doesn’t help organize the code inside commands and packages. Large programs have many concerns and files beyond just Go files.

The comprehensive approach

The comprehensive approach advocates a separate top-level directory for every major aspect of the program. What are those aspects can differ from project to project. Check out https://github.com/golang-standards/project-layout for an extreme variant with 19 top-level directories. Of course you don’t have to use ALL those directories.

The multi-git directory structure

For multi-git, we chose a pretty minimal directory structure with just three top-level directories: cmd, pkg, and e2e. We know all about cmd and pkg, but what is e2e? It’s a directory that contains end-to-end tests. Those tests don’t belong in a package and I don’t want to add them to the cmd directory where they will be mixed with other executables. Without further ado, here is the new multi-git top-level directory structure:

$ tree -L 1
.
├── LICENSE
├── README.md
├── main.go
├── cmd
├── pkg
├── e2e

Conclusion

A consistent and well-organized directory structure is essential for large programs developed by multiple developers. Go has several distinct elements such as packages and commands that it makes sense to organize in separate directory hierarchies. There are several popular directory organization schemes in the Go community, but no formal standard. For multi-git, we will use a simple directory structure with top-level directories for commands, packages, and end-to-end tests.

Quiz

Get hands-on with 1200+ tech skills courses.