Standard Go Project Layout

Standard Go Project Layout

Translations:

Overview

This is a basic layout for Go application projects. It's not an official standard defined by the core Go dev team; however, it is a set of common historical and emerging project layout patterns in the Go ecosystem. Some of these patterns are more popular than others. It also has a number of small enhancements along with several supporting directories common to any large enough real world application.

If you are trying to learn Go or if you are building a PoC or a toy project for yourself this project layout is an overkill. Start with something really simple (a single main.go file is more than enough). As your project grows keep in mind that it'll be important to make sure your code is well structured otherwise you'll end up with a messy code with lots of hidden dependencies and global state. When you have more people working on the project you'll need even more structure. That's when it's important to introduce a common way to manage packages/libraries. When you have an open source project or when you know other projects import the code from your project repository that's when it's important to have private (aka internal) packages and code. Clone the repository, keep what you need and delete everything else! Just because it's there it doesn't mean you have to use it all. None of these patterns are used in every single project. Even the vendor pattern is not universal.

With Go 1.14 Go Modules are finally ready for production. Use Go Modules unless you have a specific reason not to use them and if you do then you don’t need to worry about $GOPATH and where you put your project. The basic go.mod file in the repo assumes your project is hosted on GitHub, but it's not a requirement. The module path can be anything though the first module path component should have a dot in its name (the current version of Go doesn't enforce it anymore, but if you are using slightly older versions don't be surprised if your builds fail without it). See Issues 37554 and 32819 if you want to know more about it.

This project layout is intentionally generic and it doesn't try to impose a specific Go package structure.

This is a community effort. Open an issue if you see a new pattern or if you think one of the existing patterns needs to be updated.

If you need help with naming, formatting and style start by running gofmt and golint. Also make sure to read these Go code style guidelines and recommendations:

See Go Project Layout for additional background information.

More about naming and organizing packages as well as other code structure recommendations:

A Chinese Post about Package-Oriented-Design guidelines and Architecture layer

Go Directories

/cmd

Main applications for this project.

The directory name for each application should match the name of the executable you want to have (e.g., /cmd/myapp).

Don't put a lot of code in the application directory. If you think the code can be imported and used in other projects, then it should live in the /pkg directory. If the code is not reusable or if you don't want others to reuse it, put that code in the /internal directory. You'll be surprised what others will do, so be explicit about your intentions!

It's common to have a small main function that imports and invokes the code from the /internal and /pkg directories and nothing else.

See the /cmd directory for examples.

/internal

Private application and library code. This is the code you don't want others importing in their applications or libraries. Note that this layout pattern is enforced by the Go compiler itself. See the Go 1.4 release notes for more details. Note that you are not limited to the top level internal directory. You can have more than one internal directory at any level of your project tree.

You can optionally add a bit of extra structure to your internal packages to separate your shared and non-shared internal code. It's not required (especially for smaller projects), but it's nice to have visual clues showing the intended package use. Your actual application code can go in the /internal/app directory (e.g., /internal/app/myapp) and the code shared by those apps in the /internal/pkg directory (e.g., /internal/pkg/myprivlib).

/pkg

Library code that's ok to use by external applications (e.g., /pkg/mypubliclib). Other projects will import these libraries expecting them to work, so think twice before you put something here :-) Note that the internal directory is a better way to ensure your private packages are not importable because it's enforced by Go. The /pkg directory is still a good way to explicitly communicate that the code in that directory is safe for use by others. The I'll take pkg over internal blog post by Travis Jeffery provides a good overview of the pkg and internal directories and when it might make sense to use them.

It's also a way to group Go code in one place when your root directory contains lots of non-Go components and directories making it easier to run various Go tools (as mentioned in these talks: Best Practices for Industrial Programming from GopherCon EU 2018, GopherCon 2018: Kat Zien - How Do You Structure Your Go Apps and GoLab 2018 - Massimiliano Pippi - Project layout patterns in Go).

See the /pkg directory if you want to see which popular Go repos use this project layout pattern. This is a common layout pattern, but it's not universally accepted and some in the Go community don't recommend it.

It's ok not to use it if your app project is really small and where an extra level of nesting doesn't add much value (unless you really want to :-)). Think about it when it's getting big enough and your root directory gets pretty busy (especially if you have a lot of non-Go app components).

/vendor

Application dependencies (managed manually or by your favorite dependency management tool like the new built-in Go Modules feature). The go mod vendor command will create the /vendor directory for you. Note that you might need to add the -mod=vendor flag to your go build command if you are not using Go 1.14 where it's on by default.

Don't commit your application dependencies if you are building a library.

Note that since 1.13 Go also enabled the module proxy feature (using https://proxy.golang.org as their module proxy server by default). Read more about it here to see if it fits all of your requirements and constraints. If it does, then you won't need the vendor directory at all.

Service Application Directories

/api

OpenAPI/Swagger specs, JSON schema files, protocol definition files.

See the /api directory for examples.

Web Application Directories

/web

Web application specific components: static web assets, server side templates and SPAs.

Common Application Directories

/configs

Configuration file templates or default configs.

Put your confd or consul-template template files here.

/init

System init (systemd, upstart, sysv) and process manager/supervisor (runit, supervisord) configs.

/scripts

Scripts to perform various build, install, analysis, etc operations.

These scripts keep the root level Makefile small and simple (e.g., https://github.com/hashicorp/terraform/blob/master/Makefile).

See the /scripts directory for examples.

/build

Packaging and Continuous Integration.

Put your cloud (AMI), container (Docker), OS (deb, rpm, pkg) package configurations and scripts in the /build/package directory.

Put your CI (travis, circle, drone) configurations and scripts in the /build/ci directory. Note that some of the CI tools (e.g., Travis CI) are very picky about the location of their config files. Try putting the config files in the /build/ci directory linking them to the location where the CI tools expect them (when possible).

/deployments

IaaS, PaaS, system and container orchestration deployment configurations and templates (docker-compose, kubernetes/helm, mesos, terraform, bosh). Note that in some repos (especially apps deployed with kubernetes) this directory is called /deploy.

/test

Additional external test apps and test data. Feel free to structure the /test directory anyway you want. For bigger projects it makes sense to have a data subdirectory. For example, you can have /test/data or /test/testdata if you need Go to ignore what's in that directory. Note that Go will also ignore directories or files that begin with "." or "_", so you have more flexibility in terms of how you name your test data directory.

See the /test directory for examples.

Other Directories

/docs

Design and user documents (in addition to your godoc generated documentation).

See the /docs directory for examples.

/tools

Supporting tools for this project. Note that these tools can import code from the /pkg and /internal directories.

See the /tools directory for examples.

/examples

Examples for your applications and/or public libraries.

See the /examples directory for examples.

/third_party

External helper tools, forked code and other 3rd party utilities (e.g., Swagger UI).

/githooks

Git hooks.

/assets

Other assets to go along with your repository (images, logos, etc).

/website

This is the place to put your project's website data if you are not using GitHub pages.

See the /website directory for examples.

Directories You Shouldn't Have

/src

Some Go projects do have a src folder, but it usually happens when the devs came from the Java world where it's a common pattern. If you can help yourself try not to adopt this Java pattern. You really don't want your Go code or Go projects to look like Java :-)

Don't confuse the project level /src directory with the /src directory Go uses for its workspaces as described in How to Write Go Code. The $GOPATH environment variable points to your (current) workspace (by default it points to $HOME/go on non-windows systems). This workspace includes the top level /pkg, /bin and /src directories. Your actual project ends up being a sub-directory under /src, so if you have the /src directory in your project the project path will look like this: /some/path/to/workspace/src/your_project/src/your_code.go. Note that with Go 1.11 it's possible to have your project outside of your GOPATH, but it still doesn't mean it's a good idea to use this layout pattern.

Badges

  • Go Report Card - It will scan your code with gofmt, go vet, gocyclo, golint, ineffassign, license and misspell. Replace github.com/golang-standards/project-layout with your project reference.

    Go Report Card

  • GoDoc - It will provide online version of your GoDoc generated documentation. Change the link to point to your project.

    Go Doc

  • Pkg.go.dev - Pkg.go.dev is a new destination for Go discovery & docs. You can create a badge using the badge generation tool.

    PkgGoDev

  • Release - It will show the latest release number for your project. Change the github link to point to your project.

    Release

Notes

A more opinionated project template with sample/reusable configs, scripts and code is a WIP.

Comments
  • Missing simple approach to building and vendoring

    Missing simple approach to building and vendoring

    Pulling out my hair to do something as simple (or in go- complex) as using dep, gb and make to perform a simple build of a repo with this structure. Even if its opinionated it would help to show

    • a Makefile including gb (the refs are good but much too complex for a beginner)
    • a way to use dep for installing dependencies as part of the make process
  • Using docker while every service in cmd directory is another image

    Using docker while every service in cmd directory is another image

    Hello, I'm struggling with building each /cmd/* separately, not as a single image, and I'm not able to build it when context directory doesn't have go.mod itself. Have anyone managed to use Docker with this layout?

  • Not clear where to put files containing secrets

    Not clear where to put files containing secrets

    I've a service account file generated by Google which contains (secret) keys. I can't conclude from the current setup where to put these into.

    My first idea was configs. But for me, configs can be public.

  • Golang has the concept of models/services/repo?

    Golang has the concept of models/services/repo?

    Can I use models/services/repositories folder inside /internal? I mean, I know we can use, but theres a golang way of using this? I know this is a concept from other languages such Java (which is mine, and my team background) , but where should we put structs that looks like a model?

  • Golang API: Code from other languages ?

    Golang API: Code from other languages ?

    Hello,

    I'm currently developing a RESTful API in Go and I'm using this helpful layout to organize my project. However, I'm more comfortable in placing other language client code (by example, Python) to access this API into the main project in order to keep consistency between version.

    So I got two questions :

    • Is this really a good idea or should I separate the Golang project from its client in other languages ?
    • If this is not a bad idea, in which folder should I place this code ?

    Thank you very much :smiley:

  • How to use this layout for a gRPC API Microservice Project?

    How to use this layout for a gRPC API Microservice Project?

    It would be really helpful if you can give an example on how to use this layout for gRPC based microservice systems, since gRPC and Microservices are quiet common now a days.

  • No src folder although the official guide tells to?

    No src folder although the official guide tells to?

    Hey,

    I was wonderin what you think about the official Go documentation, which recommends creating a src folder, whereas you tell us not to.

    Here's the link: https://golang.org/doc/code.html

  • Guidance could be provided on where to put tests in library directories

    Guidance could be provided on where to put tests in library directories

    Hello,

    Coming from a java background (where we put source code in /src/main/my/package, and tests in src/test/my/package), it's not obvious to me how Gophers typically structure their tests. Looking at istio's source, I see a test sub directory "pkg/test", but I also see tests directly in the pkg/ level: For example: https://github.com/istio/istio/blob/master/pkg/channels/unbounded_test.go, https://github.com/istio/istio/blob/master/pkg/channels/unbounded.go.

    Perhaps a contributor to this repository can provide their opinion on where tests belong in the pkg directory's README?

  • Review of the Italian translation

    Review of the Italian translation

    While reading the Italian version I have noticed some errors, which I fixed.

    Here's a summary of the changes included in this PR:

    • In Italian, foreign words, with few exceptions, shall be in the singular form. Therefore, instead of "files", one should just write "file", even when speaking about more than one file
    • The word "perché" was using the wrong accent "è"
    • The verb È was wrongly written with an apostrophe instead of an accent
    • Some minor typos such as a wrong article and a misplaced comma.
  • Why there is no link to the Italian translations?

    Why there is no link to the Italian translations?

    Hi, I came across this repo and find it really useful. I want to help with the Italian translation but I saw that, even though an Italian translation is present, there is no link in the README.md. Is there any reason why?

  • Driver location

    Driver location

    Where would drivers written in Go belong in the project structure?

    The only place which kinda makes sense from what I read might be /third_party maybe have a /third_party/drivers?

    Also where would FUSE file systems belong?

Standard Go Project Layout

Standard Go Project Layout Translations: 한국어 문서 简体中文 正體中文 简体中文 - ??? Français 日本語 Portuguese Español Overview This is a basic layout for Go applicatio

Jan 2, 2023
Standard Go Project Layout
Standard Go Project Layout

This is a basic layout for Go application projects. It's not an official standard defined by the core Go dev team; however, it is a set of common historical and emerging project layout patterns in the Go ecosystem. Some of these patterns are more popular than others. It also has a number of small enhancements along with several supporting directories common to any large enough real world application.

Jan 3, 2023
Idiomatic Go input parsing with subcommands, positional values, and flags at any position. No required project or package layout and no external dependencies.
Idiomatic Go input parsing with subcommands, positional values, and flags at any position. No required project or package layout and no external dependencies.

Sensible and fast command-line flag parsing with excellent support for subcommands and positional values. Flags can be at any position. Flaggy has no

Jan 1, 2023
Go Project Sample Layout

go-sample A sample layout for Go application projects with the real code. Where it all comes from? Ideas used to create the architecture and structure

Dec 26, 2022
Go Todo Backend example using modular project layout for product microservice.

go-todo-backend Go Todo Backend Example Using Modular Project Layout for Product Microservice. It's suitable as starting point for a medium to larger

Dec 29, 2022
Generate scaffold project layout for Go.

scaffold Scaffold generates starter Go project layout. Let you can focus on buesiness logic implemeted. The following is Go project layout scaffold ge

Dec 11, 2022
go:embed and the golang-standards project layout

An example of using the golang-standards project layout and the go:embed directive.

May 17, 2022
A practical Golang project layout

Golayout Golayout is a boilerplate project that containing the usage of the best practice and popular components. The code organization follows the st

Jul 12, 2022
🔑A high performance Key/Value store written in Go with a predictable read/write performance and high throughput. Uses a Bitcask on-disk layout (LSM+WAL) similar to Riak.

bitcask A high performance Key/Value store written in Go with a predictable read/write performance and high throughput. Uses a Bitcask on-disk layout

Sep 26, 2022
Kratos Service Layout

Kratos Layout Install Kratos

Jan 1, 2023
Go structure annotations that supports encoding and decoding; similar to C-style bitfields. Supports bitfield packing, self-describing layout parameters, and alignment.
Go structure annotations that supports encoding and decoding; similar to C-style bitfields. Supports bitfield packing, self-describing layout parameters, and alignment.

STRUCTure EXtensions structex provides annotation rules that extend Go structures for implementation of encoding and decoding of byte backed data fram

Oct 13, 2022
Grab is a tool that downloads source code repositories into a convenient directory layout created from the repo's URL's domain and path

Grab is a tool that downloads source code repositories into a convenient directory layout created from the repo's URL's domain and path. It supports Git, Mercurial (hg), Subversion, and Bazaar repositories.

Jun 2, 2022
This is an example of a keep-it-simple directory layout for Go projects that was created using DDD principles, please copy and share if you like it.

DDD Go Template This project was created to illustrate a great architectural structure I developed together with @fabiorodrigues in the period I was w

Dec 5, 2022
🔮 Graph Layout Algorithms in Go

Graph Layout Algorithms in Go This module provides algorithms for graph visualization in native Go. As of 2021-11-20, virtually all graph visualizatio

Dec 4, 2022
Memory-Alignment: a tool to help analyze layout of fields in struct in memory
Memory-Alignment: a tool to help analyze layout of fields in struct in memory

Memory Alignment Memory-Alignment is a tool to help analyze layout of fields in struct in memory. Usage go get github.com/vearne/mem-aligin Example p

Oct 26, 2022
Helps you enforce a layout per workspace

i3-layout-per-workspace This tool will allow you to force a layout on a workspac

Feb 16, 2022
The standard library flag package with its missing features

cmd Package cmd is a minimalistic library that enables easy sub commands with the standard flag library. This library extends the standard library fla

Oct 4, 2022
A cross platform package that follows the XDG Standard

XDG A cross platform package that tries to follow XDG Standard when possible. Since XDG is linux specific, I am only able to follow standards to the T

Oct 8, 2022
The slightly more awesome standard unix password manager for teams
The slightly more awesome standard unix password manager for teams

gopass Introduction gopass is a password manager for the command line written in Go. It supports all major operating systems (Linux, MacOS, BSD) as we

Jan 4, 2023
Fast and simple key/value store written using Go's standard library
Fast and simple key/value store written using Go's standard library

Table of Contents Description Usage Cookbook Disadvantages Motivation Benchmarks Test 1 Test 4 Description Package pudge is a fast and simple key/valu

Nov 17, 2022