golang-project-layout

作者: samber

提供設定 Golang 專案佈局與工作區的指引。適用於開始新的 Go 專案、整理現有程式碼庫、設定包含多個套件的單一儲存庫、建立含多個 main 套件的 CLI 工具、決定 cmd/internal/pkg 目錄慣例,或討論套件重構、套件拆分、模組拆分時使用。

npx skills add https://github.com/samber/cc-skills-golang --skill golang-project-layout

Persona: You are a Go project architect. You right-size structure to the problem — a script stays flat, a service gets layers only when justified by actual complexity.

Go Project Layout

Architecture Decision: Ask First

When starting a new project, ask the developer what software architecture they prefer (clean architecture, hexagonal, DDD, flat structure, etc.). NEVER over-structure small projects — a 100-line CLI tool does not need layers of abstractions or dependency injection.

→ See samber/cc-skills-golang@golang-design-patterns skill for detailed architecture guides with file trees and code examples.

Dependency Injection: Ask Next

After settling on the architecture, ask the developer which dependency injection approach they want: manual constructor injection, or a DI library (samber/do, google/wire, uber-go/dig+fx), or none at all. The choice affects how services are wired, how lifecycle (health checks, graceful shutdown) is managed, and how the project is structured. See the samber/cc-skills-golang@golang-dependency-injection skill for a full comparison and decision table.

12-Factor App

For applications (services, APIs, workers), follow 12-Factor App conventions: config via environment variables, logs to stdout, stateless processes, graceful shutdown, backing services as attached resources, and admin tasks as one-off commands (e.g., cmd/migrate/).

Quick Start: Choose Your Project Type

Project TypeUse WhenKey Directories
CLI ToolBuilding a command-line applicationcmd/{name}/, internal/, optional pkg/
LibraryCreating reusable code for otherspkg/{name}/, internal/ for private code
ServiceHTTP API, microservice, or web appcmd/{service}/, internal/, api/, web/
MonorepoMultiple related packages/modulesgo.work, separate modules per package
WorkspaceDeveloping multiple local modulesgo.work, replace directives

Module Naming Conventions

Module Name (go.mod)

Your module path in go.mod should:

  • MUST match your repository URL: github.com/username/project-name
  • Use lowercase only: github.com/you/my-app (not MyApp)
  • Use hyphens for multi-word: user-auth not user_auth or userAuth
  • Be semantic: Name should clearly express purpose

Examples:

// ✅ Good
module github.com/jdoe/payment-processor
module github.com/company/cli-tool

// ❌ Bad
module myproject
module github.com/jdoe/MyProject
module utils

Package Naming

Packages MUST be lowercase, singular, and match their directory name. → See samber/cc-skills-golang@golang-naming skill for complete package naming conventions and examples.

Directory Layout

All main packages must reside in cmd/ with minimal logic — parse flags, wire dependencies, call Run(). Business logic belongs in internal/ or pkg/. Use internal/ for non-exported packages, pkg/ only when code is useful to external consumers.

See directory layout examples for universal, small project, and library layouts, plus common mistakes.

Essential Configuration Files

Every Go project should include at the root:

  • Makefile — build automation. See Makefile template
  • .gitignore — git ignore patterns. See .gitignore template
  • .golangci.yml — linter config. See the samber/cc-skills-golang@golang-lint skill for the recommended configuration

For application configuration with Cobra + Viper, see config reference.

Tests, Benchmarks, and Examples

Co-locate _test.go files with the code they test. Use testdata/ for fixtures. See testing layout for file naming, placement, and organization details.

Go Workspaces

Use go.work when developing multiple related modules in a monorepo. See workspaces for setup, structure, and commands.

Initialization Checklist

When starting a new Go project:

  • Ask the developer their preferred software architecture (clean, hexagonal, DDD, flat, etc.)
  • Ask the developer their preferred DI approach — see samber/cc-skills-golang@golang-dependency-injection skill
  • Decide project type (CLI, library, service, monorepo)
  • Right-size the structure to the project scope
  • Choose module name (matches repo URL, lowercase, hyphens)
  • Run go version to detect the current go version
  • Run go mod init github.com/user/project-name
  • Create cmd/{name}/main.go for entry point
  • Create internal/ for private code
  • Create pkg/ only if you have public libraries
  • For monorepos: Initialize go work and add modules
  • Run gofmt -s -w . to ensure formatting
  • Add .gitignore with /vendor/ and binary patterns

Related Skills

→ See samber/cc-skills-golang@golang-cli skill for CLI tool structure and Cobra/Viper patterns. → See samber/cc-skills-golang@golang-dependency-injection skill for DI approach comparison and wiring. → See samber/cc-skills-golang@golang-lint skill for golangci-lint configuration. → See samber/cc-skills-golang@golang-continuous-integration skill for CI/CD pipeline setup. → See samber/cc-skills-golang@golang-design-patterns skill for architectural patterns.

來自 samber 的更多技能

golang-code-style
samber
Golang code style conventions — line length and breaking, variable declarations, control flow clarity, when comments help vs hurt. Use when writing or reviewing Go code, asking about style or clarity, or establishing project coding standards. Not for naming conventions (→ See `samber/cc-skills-golang@golang-naming` skill), linter configuration (→ See `samber/cc-skills-golang@golang-lint` skill), or doc comments (→ See `samber/cc-skills-golang@golang-documentation` skill).
developmentcode-review
golang-testing
samber
Production-ready Golang tests — table-driven tests, testify suites and mocks, parallel tests, fuzzing, fixtures, goroutine leak detection with goleak, snapshot testing, code coverage, integration tests, idiomatic test naming. Use when writing or reviewing Go tests, choosing a testing approach, setting up Go test CI, or debugging flaky/slow tests. For testify-specific APIs see `samber/cc-skills-golang@golang-stretchr-testify`; for measurement methodology see...
developmenttestingcode-review
golang-design-patterns
samber
符合慣例的 Golang 設計模式 — 函數選項、建構子、錯誤流程與串聯、資源管理與生命週期、優雅關閉、韌性、架構、依賴注入、資料處理、串流等。適用於明確選擇架構模式、實作函數選項、設計建構子 API、設定優雅關閉、應用韌性模式,或詢問哪種慣用 Go 模式適合特定問題時。
developmentdesigncode-review
golang-error-handling
samber
Idiomatic Golang error handling — creation, wrapping with %w, errors.Is/As, errors.Join, custom error types, sentinel errors, panic/recover, the single handling rule, structured logging with slog, HTTP request logging middleware, and samber/oops for production errors. Built to make logs usable at scale with log aggregation 3rd-party tools. Apply when creating, wrapping, inspecting, or logging errors in Go code. For samber/oops specifics → See `samber/cc-skills-golang@golang-samber-oops`...
developmentcode-review
golang-performance
samber
Golang 性能優化模式與方法論 - 若遇到 X 瓶頸,則應用 Y。涵蓋減少分配、CPU 效率、記憶體佈局、GC 調校、池化、快取以及熱路徑優化。適用於當性能分析或基準測試已識別出瓶頸,且需要正確的優化模式來解決時。亦適用於進行性能代碼審查時,提出改進建議或可協助快速識別性能增益的基準測試。不適用於測量方法論(→...
developmentcode-review
golang-security
samber
Golang的安全最佳實踐與漏洞防範。涵蓋注入攻擊(SQL、命令、XSS)、密碼學、檔案系統安全、網路安全、Cookie、機密管理、記憶體安全及日誌記錄。適用於撰寫、審查或稽核Go程式碼的安全性,或處理涉及加密、I/O、機密管理、使用者輸入處理或身分驗證的高風險程式碼。包含安全工具的配置。
securitycode-reviewdevelopment
golang-database
samber
Go 資料庫存取的全面指南 — 參數化查詢、結構掃描、可空欄位、交易、隔離層級、SELECT FOR UPDATE、連線池、批次處理、上下文傳遞與遷移工具。適用於撰寫、審查或除錯與 PostgreSQL、MariaDB、MySQL 或 SQLite 互動的 Golang 程式碼;資料庫測試;或關於 database/sql、sqlx 或 pgx 的問題。不產生資料庫結構或遷移 SQL。
developmentdatabase
golang-lint
samber
針對 Golang 專案的 lint 最佳實務與 golangci-lint 配置 — 執行 linter、設定 .golangci.yml、使用 nolint 指令抑制警告、解讀 lint 輸出,以及選擇 linter。適用於配置 golangci-lint、詢問 lint 警告或 nolint 抑制方式、設定程式碼品質工具,或挑選 linter 時。亦適用於使用者提及 golangci-lint、go vet、staticcheck 或 revive 時。
developmentcode-reviewtesting