Go Project Layout
Structure follows size. The biggest layout mistake in Go is copying a
microservice skeleton for a 500-line tool — or growing a 50-package
service inside a flat directory. Match the layout to the project.
1. Pick the Layout by Project Size
| Project |
Layout |
| Small tool, single binary, <5 files |
Flat: everything in package main at the root |
| Library for others to import |
Root package named after the module, internal/ for helpers |
| Service with one binary |
cmd/<name>/main.go + internal/ packages |
| Multiple binaries sharing code |
cmd/<name1>/, cmd/<name2>/ + internal/ |
Never start with empty pkg/, api/, docs/, build/ directories
"for later". Add structure when the code demands it, not before.
2. Module Naming
# ✅ Good — repository path, lowercase
go mod init github.com/acme/payment-service
# ❌ Bad — not fetchable, uppercase, or vanity without DNS
go mod init PaymentService
go mod init payment_service
The last path element should match what users will see: for a library,
it becomes the default import name.
3. Service Layout (the default for APIs and workers)
payment-service/
├── cmd/
│ └── payment-api/
│ └── main.go # flag/env parsing, wiring, Run() — nothing else
├── internal/
│ ├── domain/ # core types, business rules; zero external deps
│ ├── service/ # use cases orchestrating domain + stores
│ ├── store/ # data access implementations (postgres/, redis/)
│ ├── handler/ # HTTP/gRPC adapters
│ └── config/ # config loading and validation
├── migrations/ # if the service owns a database
├── go.mod
├── Makefile
└── README.md
Rules:
internal/ by default — the compiler enforces that nobody outside the
module imports it. Promote to a public package only on demand.
pkg/ only when external consumers exist AND the module also has
private code. When in doubt, don't create it.
- Dependencies point inward:
handler → service → domain ← store.
domain imports neither store nor handler.
4. Thin main, Runnable Run
Keep main.go to wiring plus a delegating call, so the app is testable:
func main() {
if err := run(context.Background(), os.Args[1:], os.Getenv); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
func run(ctx context.Context, args []string, getenv func(string) string) error {
cfg, err := config.Load(getenv)
if err != nil {
return fmt.Errorf("load config: %w", err)
}
db, err := store.Open(ctx, cfg.DatabaseURL)
if err != nil {
return fmt.Errorf("open db: %w", err)
}
defer db.Close()
svc := service.New(store.NewUserRepo(db))
srv := handler.NewServer(cfg.Addr, svc)
return srv.ListenAndServe(ctx)
}
os.Exit appears exactly once, in main.
run takes its dependencies (args, getenv) so tests can call it.
- No
init() functions for wiring — explicit construction order only.
5. Library Layout
retry/
├── retry.go # package retry — the API, in the root
├── retry_test.go
├── backoff.go # same package, split by topic
├── internal/
│ └── clock/ # implementation details users must not import
├── examples_test.go # Example* functions shown in godoc
└── go.mod
- The root directory IS the package. No
src/, no lib/.
- One package per concept. Resist
util, common, helpers — name
packages after what they provide (retry, clock, httpsign).
6. Naming Rules for Directories and Packages
- Package name == directory name, short, lowercase, no underscores:
store/postgres, not store/postgres_impl.
- Don't stutter:
payment.Service, not payment.PaymentService.
- Binary names in
cmd/ are user-facing: cmd/payment-api,
hyphenated is fine (directory only holds package main).
7. Files That Belong at the Root
go.mod, go.sum, README.md, LICENSE, Makefile,
.golangci.yml, Dockerfile (single-binary projects).
- Do NOT create:
src/ (un-idiomatic), vendor/ (unless the team
explicitly vendors), one-file packages like types/ or models/
that become dumping grounds.
Scaffolding Procedure
- Ask/decide: tool, library, or service? How many binaries?
go mod init <repo-path>.
- Create only the directories the first feature needs.
- Write
main.go with the thin-main pattern above.
- Add
Makefile targets: build, test, lint.
- Verify:
go build ./... and go vet ./... pass on the skeleton.
Verification Checklist
- Layout matches project size — no empty scaffolding directories
- Module path is the fetchable repository path
- All non-public packages live under
internal/
main.go is thin: parse, wire, call run, exit
os.Exit only in main; no wiring in init()
- Dependencies flow inward;
domain has zero infrastructure imports
- No
util/common/helpers/models grab-bag packages
- Package names match directories, lowercase, no stutter
go build ./... passes on the fresh skeleton
1---
2name: go-project-layout
3description: >
4 Scaffold new Go projects and services: directory structure, cmd/ and
5 internal/ conventions, when to use a flat layout, module naming, and main
6 package wiring. Use when: "new Go project", "scaffold a service", "create
7 project structure", "start a Go module", "how do I organize a new
8 service", "set up folder structure".
9 Not for: reviewing an existing architecture (go-architecture-review), DI
10 wiring (go-dependency-injection), CI setup (go-ci).
11user-invocable: true
12license: MIT
13compatibility: Designed for Claude Code or similar AI coding agents working on Go projects. Requires the Go toolchain. Requires git for repository initialisation.
14allowed-tools: Read Edit Write Glob Grep Bash(go:*) Bash(gofmt:*) Bash(git:*)
15metadata:
16 source: https://skillmd.com/skills/gabrielmoreira/go-project-layout
17 author: eduardo-sl
18 version: "1.1.1"
19---
20
21# Go Project Layout
22
23Structure follows size. The biggest layout mistake in Go is copying a
24microservice skeleton for a 500-line tool — or growing a 50-package
25service inside a flat directory. Match the layout to the project.
26
27## 1. Pick the Layout by Project Size
28
29| Project | Layout |
30|---|---|
31| Small tool, single binary, <5 files | Flat: everything in package `main` at the root |
32| Library for others to import | Root package named after the module, `internal/` for helpers |
33| Service with one binary | `cmd/<name>/main.go` + `internal/` packages |
34| Multiple binaries sharing code | `cmd/<name1>/`, `cmd/<name2>/` + `internal/` |
35
36Never start with empty `pkg/`, `api/`, `docs/`, `build/` directories
37"for later". Add structure when the code demands it, not before.
38
39## 2. Module Naming
40
41```bash
42# ✅ Good — repository path, lowercase
43go mod init github.com/acme/payment-service
44
45# ❌ Bad — not fetchable, uppercase, or vanity without DNS
46go mod init PaymentService
47go mod init payment_service
48```
49
50The last path element should match what users will see: for a library,
51it becomes the default import name.
52
53## 3. Service Layout (the default for APIs and workers)
54
55```text
56payment-service/
57├── cmd/
58│ └── payment-api/
59│ └── main.go # flag/env parsing, wiring, Run() — nothing else
60├── internal/
61│ ├── domain/ # core types, business rules; zero external deps
62│ ├── service/ # use cases orchestrating domain + stores
63│ ├── store/ # data access implementations (postgres/, redis/)
64│ ├── handler/ # HTTP/gRPC adapters
65│ └── config/ # config loading and validation
66├── migrations/ # if the service owns a database
67├── go.mod
68├── Makefile
69└── README.md
70```
71
72Rules:
73
74- `internal/` by default — the compiler enforces that nobody outside the
75 module imports it. Promote to a public package only on demand.
76- `pkg/` only when external consumers exist AND the module also has
77 private code. When in doubt, don't create it.
78- Dependencies point inward: `handler → service → domain ← store`.
79 `domain` imports neither `store` nor `handler`.
80
81## 4. Thin main, Runnable Run
82
83Keep `main.go` to wiring plus a delegating call, so the app is testable:
84
85```go
86func main() {
87 if err := run(context.Background(), os.Args[1:], os.Getenv); err != nil {
88 fmt.Fprintln(os.Stderr, err)
89 os.Exit(1)
90 }
91}
92
93func run(ctx context.Context, args []string, getenv func(string) string) error {
94 cfg, err := config.Load(getenv)
95 if err != nil {
96 return fmt.Errorf("load config: %w", err)
97 }
98
99 db, err := store.Open(ctx, cfg.DatabaseURL)
100 if err != nil {
101 return fmt.Errorf("open db: %w", err)
102 }
103 defer db.Close()
104
105 svc := service.New(store.NewUserRepo(db))
106 srv := handler.NewServer(cfg.Addr, svc)
107 return srv.ListenAndServe(ctx)
108}
109```
110
111- `os.Exit` appears exactly once, in `main`.
112- `run` takes its dependencies (`args`, `getenv`) so tests can call it.
113- No `init()` functions for wiring — explicit construction order only.
114
115## 5. Library Layout
116
117```text
118retry/
119├── retry.go # package retry — the API, in the root
120├── retry_test.go
121├── backoff.go # same package, split by topic
122├── internal/
123│ └── clock/ # implementation details users must not import
124├── examples_test.go # Example* functions shown in godoc
125└── go.mod
126```
127
128- The root directory IS the package. No `src/`, no `lib/`.
129- One package per concept. Resist `util`, `common`, `helpers` — name
130 packages after what they provide (`retry`, `clock`, `httpsign`).
131
132## 6. Naming Rules for Directories and Packages
133
134- Package name == directory name, short, lowercase, no underscores:
135 `store/postgres`, not `store/postgres_impl`.
136- Don't stutter: `payment.Service`, not `payment.PaymentService`.
137- Binary names in `cmd/` are user-facing: `cmd/payment-api`,
138 hyphenated is fine (directory only holds package `main`).
139
140## 7. Files That Belong at the Root
141
142- `go.mod`, `go.sum`, `README.md`, `LICENSE`, `Makefile`,
143 `.golangci.yml`, `Dockerfile` (single-binary projects).
144- Do NOT create: `src/` (un-idiomatic), `vendor/` (unless the team
145 explicitly vendors), one-file packages like `types/` or `models/`
146 that become dumping grounds.
147
148## Scaffolding Procedure
149
1501. Ask/decide: tool, library, or service? How many binaries?
1512. `go mod init <repo-path>`.
1523. Create only the directories the first feature needs.
1534. Write `main.go` with the thin-main pattern above.
1545. Add `Makefile` targets: `build`, `test`, `lint`.
1556. Verify: `go build ./...` and `go vet ./...` pass on the skeleton.
156
157## Verification Checklist
158
1591. Layout matches project size — no empty scaffolding directories
1602. Module path is the fetchable repository path
1613. All non-public packages live under `internal/`
1624. `main.go` is thin: parse, wire, call `run`, exit
1635. `os.Exit` only in `main`; no wiring in `init()`
1646. Dependencies flow inward; `domain` has zero infrastructure imports
1657. No `util`/`common`/`helpers`/`models` grab-bag packages
1668. Package names match directories, lowercase, no stutter
1679. `go build ./...` passes on the fresh skeleton