Idiomatic Code Organization
Swipe to show menu
Go Project Structure
Organize your Go projects using the following structure for clarity and maintainability:
- Place the main entry point in a
cmd/directory; - Store application code in an
internal/directory for private packages; - Keep reusable packages in a
pkg/directory; - Group configuration files and assets in a
configs/orassets/directory; - Place third-party dependencies in a
vendor/directory if vendoring is required.
A typical layout:
myapp/
βββ cmd/
β βββ myapp/
β βββ main.go
βββ internal/
β βββ service/
β βββ service.go
βββ pkg/
β βββ utils/
β βββ utils.go
βββ configs/
βββ assets/
βββ go.mod
βββ go.sum
File Organization and Naming
- Use one package per directory; name the directory after the package;
- Name files to reflect their purpose, such as
http.go,db.go, orservice.go; - Keep related types and functions together for discoverability;
- Avoid stutter by matching package and type names (e.g.,
user.Useris redundant, preferuser.Model).
Package Design Principles
- Keep packages focused on a single responsibility;
- Expose only what is necessary: use lowercase for unexported identifiers and uppercase for exported ones;
- Avoid circular dependencies between packages;
- Document packages and exported functions using Go doc comments.
Best Practices for Clean Code
- Write short, focused functions;
- Use clear, descriptive names for variables and functions;
- Prefer composition over inheritance;
- Handle errors explicitly and consistently;
- Write tests alongside your code in
*_test.gofiles.
Following these conventions makes your Go projects easier to understand, test, and maintain as they grow.
Everything was clear?
Thanks for your feedback!
SectionΒ 2. ChapterΒ 4
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat
SectionΒ 2. ChapterΒ 4