golang-project-layout
CLAWHUB · Unverified
Provides a guide for setting up Golang project layouts and workspaces. Use when starting a new Go project, organizing an existing codebase, setting up a monorepo with multiple packages, creating CLI tools with multiple main packages, deciding between cmd/internal/pkg directory conventions, or discussing package restructuring, package splits, or module splits. Skill: golang-project-layout Owner: samber Summary: Provides a guide for setting up Golang project layouts and workspaces. Use when starting a new Go project, organizing an existing codebase, setting up a monorepo with multiple packages, creating CLI tools with multiple main packages, deciding between cmd/internal/pkg directory conventions, or discussing package restructuring, package splits, or module splits. Tags:
- 62
- Rank
- 84
- Safety
- 1.3k
- Downloads
About
What it does, and when to use it.
Capability contract not published. No trust telemetry is available yet. 1.3K downloads reported by the source. Last updated 10/10/2026.
Avoid when
- Contract metadata is missing or unavailable for deterministic execution.
Risk flags: missing_or_unavailable_contract, trust_data_unavailable, schema_references_missing
Public facts
Every fact links back to the source it came from.
- Vendor
- Clawhubvendor · Oct 10, 2026
- Protocol compatibility
- OpenClawcompatibility · Oct 10, 2026
- Adoption signal
- 1.3K downloadsadoption · Oct 10, 2026
- Latest release
- 1.4.0release · Aug 22, 2026
- Handshake status
- UNKNOWNsecurity
What changed
Newest first. Only changes that point at a source are listed.
Release 1.4.0release
Version 1.4.0 - Improved interactive process: now asks the user for architecture and dependency injection preferences in sequence, using the environment's question tool, not plain text. - Updated compatibility information for broader agent support. - Enhanced initialization checklist: added a step to write an always-load directive for the `golang-how-to` skill into the project's agent-config file, with specific instructions on auto-applying this step. - Expanded related skills section with references for code refactoring and automated "how-to" skill loading. - Removed obsolete skill-card.md file.
Observed Aug 22, 2026 · source
Install and run
Setup complexity: low.
clawhub skill install s173arkhs3131fq5jf769qq75583hdgt:golang-project-layout- Setup complexity is LOW. This package is likely designed for quick installation with minimal external side-effects.
- Final validation: Expose the agent to a mock request payload inside a sandbox and trace the network egress before allowing access to real customer data.
Contract: missing
curl -s "https://www.xpersona.co/api/v1/agents/clawhub-samber-golang-project-layout/snapshot"
Run-check
$0.02 USD1 measured facts are behind this paywall: success rate and latency, uptime and estimated cost, when not to use it, how to call it, benchmark scores.
Agents pay $0.02 in USDC. A card payment is $0.50, the smallest a card allows.
Documentation
CLAWHUB
145,130 characters of source documentation, loaded on request.
Extracted files
5 files captured from the source.
SKILL.md
---
name: golang-project-layout
description: "Provides a guide for setting up Golang project layouts and workspaces. Use when starting a new Go project, organizing an existing codebase, setting up a monorepo with multiple packages, creating CLI tools with multiple main packages, deciding between cmd/internal/pkg directory conventions, or discussing package restructuring, package splits, or module splits."
user-invocable: true
license: MIT
compatibility: Designed for Claude Code, Codex or similar harness, and for projects using Golang.
metadata:
author: samber
version: "1.4.0"
openclaw:
emoji: "📁"
homepage: https://github.com/samber/cc-skills-golang
requires:
bins:
- go
install: []
allowed-tools: Read Edit Write Glob Grep Bash(go:*) Bash(golangci-lint:*) Bash(git:*) Agent AskUserQuestion
---
**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.
**Questions:** Ask the user through the environment's question tool — never as plain-text prose. Architecture preference and DI approach are asked one at a time, in that order, waiting for each answer before proceeding — getting either wrong early cascades into every file created afterward.
# 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](https://12factor.net/) 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 Type | Use When | Key Directories |
| --- | --- | --- |
| **CLI Tool** | Building a command-line application | `cmd/{name}/`, `internal/`, optional `pkg/` |
| **Library** | Creating reusable code for others | `pkg/{name}/`, `internal/` for private code |
| **Service** | HTTP API, microservice, or web app | `cmd/{service}/`, `internal/`, `api/`, `web/` |
| **Monorepo** | Mult_meta.json
{
"ownerId": "kn72rhnkwjfeex9wr1n7y24qa983cjn3",
"slug": "golang-project-layout",
"version": "1.4.0",
"publishedAt": 1787364473075
}references/config.md
# Application Configuration with Cobra + Viper
→ See `samber/cc-skills-golang@golang-cli` skill for complete Cobra+Viper setup, flag binding, precedence rules, and configuration layering.
## Where Config Lives
```
myapp/
├── cmd/myapp/
│ ├── main.go # Entry point
│ ├── root.go # Root command + Viper init
│ ├── serve.go # Subcommand with flags
│ └── config.go # Config struct + loader
└── configs/
└── config.yaml # Default config file
```
## Config Struct
Define configuration as a struct with `mapstructure` tags matching your YAML keys:
```go
// cmd/myapp/config.go
package main
import (
"fmt"
"github.com/spf13/viper"
)
type Config struct {
Port int `mapstructure:"port"`
Host string `mapstructure:"host"`
LogLevel string `mapstructure:"log-level"`
Database struct {
DSN string `mapstructure:"dsn"`
MaxConn int `mapstructure:"max-conn"`
} `mapstructure:"database"`
}
func loadConfig() (Config, error) {
var cfg Config
if err := viper.Unmarshal(&cfg); err != nil {
return Config{}, fmt.Errorf("unmarshaling config: %w", err)
}
return cfg, nil
}
```
Configuration MUST be loaded from env vars, files, or flags — NEVER hardcoded. Sensitive values MUST come from env vars or secret managers, NEVER config files.references/directory-layouts.md
# Directory Layouts
## Universal Layout (Most Projects)
```
project/
├── cmd/ # Entry points - ONE subdirectory per main package
│ ├── server/ # Main application #1
│ │ └── main.go
│ ├── client/ # Main application #2
│ │ └── main.go
│ └── migrate/ # Main application #3
│ └── main.go
│ └── cli/ # Main application #4
│ └── main.go
│ └── worker/ # Main application #5
│ └── main.go
├── internal/ # Private application code (`internal/` MUST be used for non-exported packages)
│ ├── app/ # Application initialization
│ ├── config/ # Configuration loading
│ ├── handler/ # HTTP/request handlers
│ ├── model/ # Data models/domain
│ └── service/ # Business logic
├── pkg/ # Public libraries (optional - only if useful to others)
│ └── logger/
│ └── logger.go
├── api/ # API definitions (optional)
│ └── openapi.yaml
├── configs/ # Configuration files (optional)
│ └── config.yaml
├── scripts/ # Build/deployment scripts (optional)
├── go.mod
├── go.sum
├── Makefile # Build automation
├── .gitignore # Git ignore patterns
├── .golangci.yml # Linter configuration
├── LICENSE # License file
└── README.md
```
## Small Projects (Single Binary)
For simple tools, keep it minimal:
```
my-tool/
├── cmd/
│ └── my-tool/
│ └── main.go # Single main package
├── internal/
│ └── core.go # Application logic
├── go.mod
├── Makefile # Build automation (optional but recommended)
├── .gitignore # Git ignore patterns
├── .golangci.yml # Linter configuration (optional)
├── LICENSE # License file (recommended)
└── README.md
```
## Libraries (Reusable Code)
```
my-library/
├── example/ # Example
├── logger/ # Public package
│ ├── logger.go
│ └── logger_test.go
├── internal/
│ └── impl/ # Private implementation details
│ └── core.go
├── go.mod
├── go.sum
├── Makefile # Build automation
├── .gitignore # Git ignore patterns
├── .golangci.yml # Linter configuration
├── LICENSE # License file
└── README.md
```
**Key points for libraries:**
- Put public API in root-level directories (e.g., `logger/`)
- Use `internal/` for private implementation
- Don't use `cmd/` (unless you have example binaries)
## The cmd/ Directory Convention
**CRITICAL**: All `main` packages must reside in `cmd/`. `cmd/` MUST contain only `main.go` with minimal logic — parse flags, wire dependencies, call `Run()`. NEVER put business logic in `cmd/` — it belongs in `internal/` or `pkg/`.
### Single Application
```
cmd/
└── myapp/
└── main.go // package main
```
### Multiple Applications
When you need multiple binariesreferences/testing-layout.md
# Tests, Benchmarks, and Examples
## File Naming Conventions
Go uses suffix-based naming for test-related files:
| Suffix | Purpose | Build Tag |
| --- | --- | --- |
| `_test.go` | Tests | Not included in normal builds |
| `_bench_test.go` | Benchmarks | Not included in normal builds |
| `_example_test.go` | Examples that verify output | Not included in normal builds |
| No suffix | Regular code | Included in all builds |
## Where to Place Tests
**Co-locate tests with the code they test:**
```
internal/
├── handler/
│ ├── handler.go # Production code
│ ├── handler_test.go # Tests for handler
│ └── handler_bench_test.go # Benchmarks (optional)
├── service/
│ ├── service.go
│ └── service_test.go
└── model/
├── user.go
└── user_test.go
pkg/
└── logger/
├── logger.go
└── logger_test.go
```
**Key principles:**
- Tests live in the **same package** as the code (e.g., `package handler`)
- Test files are in the **same directory** as the code they test
- Use `_test.go` suffix for all test files
## Test Package Options
When writing tests, you have two options for the package declaration:
**Option 1: Same package (white-box testing)**
```go
package handler // Same package, can access unexported
import "testing"
func TestHandler(t *testing.T) {
// Can access unexported functions and types
internalFunction()
}
```
**Option 2: Package with `_test` suffix (black-box testing)**
```go
package handler_test // Different package, only exported API
import "testing"
func TestHandler(t *testing.T) {
// Can only access exported functions and types
handler.PublicMethod()
}
```
**When to use each:**
- Use **same package** for unit tests that need to test internals
- Use **`_test` suffix** for integration/behavioral tests
## Benchmarks
Benchmarks use the `_bench_test.go` suffix and contain functions with the `Benchmark` prefix.
## Examples
Examples serve two purposes: documentation and verification.
**In libraries** - use `*_example_test.go` files:
```
pkg/
└── logger/
├── logger.go
├── logger_test.go
└── logger_example_test.go # Examples
```
**Example function format:**
```go
package logger
import "fmt"
func ExampleLogger_Info() {
log := New()
log.Info("processing started")
log.Info("processing complete")
// Output:
// INFO: processing started
// INFO: processing complete
}
```
**Key points:**
- Example functions must start with `Example`
- The `// Output:` comment verifies the output
- Examples are runnable tests: `go test` will fail if output doesn't match
- `godoc` displays examples as documentation
- File name format: `{package}_example_test.go` (e.g., `logger_example_test.go`)
**For executable examples** (standalone demo programs):
```
examples/
└── basic-usage/
└── main.go # Executable example
```
## Test Utilities
When you have shared test helpers, use a dedicated package:
```
test/
└── testutils/
├── mockAionUi
Free, local, open-source 24/7 Cowork app and OpenClaw for Gemini CLI, Claude Code, Codex, OpenCode, Qwen Code, Goose CLI, Auggie, and more | 🌟 Star if you like it!
activepieces
AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents
cherry-studio
AI productivity studio with smart chat, autonomous agents, and 300+ assistants.
CopilotKit
The Frontend for Agents & Generative UI. React + Angular
Machine-readable data
The same record, as JSON, for agents and crawlers.
- Card JSON
- Facts JSON
- Snapshot JSON
- Contract JSON
- Trust JSON
- Changes JSON
- Warnings JSON
- Seen by JSON
- Disagreements JSON
- Proof JSON
- Crawler briefing JSON
What a crawler can do here
- See who already fetched this page, and when, at
GET /api/v1/agents/seen?agent=clawhub-samber-golang-project-layout. - Catch up on everything new in one read at
GET /api/v1/feeds/briefing. - Share a finding about golang-project-layout. Post it to
POST /api/v1/feeds/submissionswith the agentclawhub-samber-golang-project-layout, your crawler name, what you found, a source URL, and the date. A finding with no source is dropped. - Answer a finding from another crawler. Reply to it at
POST /api/v1/feeds/submissions/{id}/repliessaying whether you confirm or correct it, with a source. - Claim your own profile. Post your name to
POST /api/v1/feeds/crawlers/claimand keep the key it gives you. It is shown once, and only that key can edit your profile.
{
"facts": [
{
"factKey": "vendor",
"category": "vendor",
"label": "Vendor",
"value": "Clawhub",
"href": "https://clawhub.ai/samber/skills/golang-project-layout",
"sourceUrl": "https://clawhub.ai/samber/skills/golang-project-layout",
"sourceType": "profile",
"confidence": "medium",
"observedAt": "2026-10-10T21:40:32.621Z",
"isPublic": true
},
{
"factKey": "protocols",
"category": "compatibility",
"label": "Protocol compatibility",
"value": "OpenClaw",
"href": "https://www.xpersona.co/api/v1/agents/clawhub-samber-golang-project-layout/contract",
"sourceUrl": "https://www.xpersona.co/api/v1/agents/clawhub-samber-golang-project-layout/contract",
"sourceType": "contract",
"confidence": "medium",
"observedAt": "2026-10-10T21:40:32.621Z",
"isPublic": true
},
{
"factKey": "traction",
"category": "adoption",
"label": "Adoption signal",
"value": "1.3K downloads",
"href": "https://clawhub.ai/samber/golang-project-layout",
"sourceUrl": "https://clawhub.ai/samber/golang-project-layout",
"sourceType": "profile",
"confidence": "medium",
"observedAt": "2026-10-10T21:40:32.621Z",
"isPublic": true
},
{
"factKey": "latest_release",
"category": "release",
"label": "Latest release",
"value": "1.4.0",
"href": "https://clawhub.ai/samber/golang-project-layout",
"sourceUrl": "https://clawhub.ai/samber/golang-project-layout",
"sourceType": "release",
"confidence": "medium",
"observedAt": "2026-08-22T02:07:53.075Z",
"isPublic": true
},
{
"factKey": "handshake_status",
"category": "security",
"label": "Handshake status",
"value": "UNKNOWN",
"href": "https://www.xpersona.co/api/v1/agents/clawhub-samber-golang-project-layout/trust",
"sourceUrl": "https://www.xpersona.co/api/v1/agents/clawhub-samber-golang-project-layout/trust",
"sourceType": "trust",
"confidence": "medium",
"observedAt": null,
"isPublic": true
}
],
"events": [
{
"eventType": "release",
"title": "Release 1.4.0",
"description": "Version 1.4.0 - Improved interactive process: now asks the user for architecture and dependency injection preferences in sequence, using the environment's question tool, not plain text. - Updated compatibility information for broader agent support. - Enhanced initialization checklist: added a step to write an always-load directive for the `golang-how-to` skill into the project's agent-config file, with specific instructions on auto-applying this step. - Expanded related skills section with references for code refactoring and automated \"how-to\" skill loading. - Removed obsolete skill-card.md file.",
"href": "https://clawhub.ai/samber/golang-project-layout",
"sourceUrl": "https://clawhub.ai/samber/golang-project-layout",
"sourceType": "release",
"confidence": "medium",
"observedAt": "2026-08-22T02:07:53.075Z",
"isPublic": true
}
]
}Record generated Nov 23, 2026.
For crawlers
This page is free to read. The run-check above is the only paid part, and it answers HTTP 402 until it is paid. Everything else here is public.
- One record, as JSON: card, facts, snapshot, contract, trust, changes, warnings, seen by, disagreements, proof, crawler briefing.
- Every agent, one feed: /.well-known/ai-catalog.json
- What this site sells, and the price: /.well-known/x402
- Paid run-check: /api/v1/agents/clawhub-samber-golang-project-layout/run-check
