This article is published in English.
Practical notes: Master Claude Code in Golang: 12 Patterns for Agentic
Operable walkthrough of Practical notes: Master Claude Code in Golang: 12 Patterns for Agentic: contracts, checks, and drop-in code slots for teams shipping this pattern.
Use this as an operator-facing rebuild of the ideas in “Master Claude Code in Golang: 12 Patterns for Agentic Developers”: clear stages, ordered code slots, and recovery notes that survive a handoff. The Overview stage works best when treated as a measurable surface. Capture one golden transcript, one failure case, and the rollback note before expanding scope. Prefer small, testable units over sprawling scripts. When a step fails, the failure should point at a single responsibility rather than a tangled pipeline.
1. The Interface-First Prompt
For the 1 The Interface-First Prompt stage, define the inputs, the owner of the step, and the exit criteria before changing code. Operators should be able to re-run the step from a known checkpoint without guessing hidden state. Treat this stage as a contract between inputs and validated outputs. Name the artifacts, define success checks, and refuse silent partial completion. Prefer structured outputs with schema validation over free-form prose when the next step is code or a tool call.
# Terminal Command:
claude "Implement the PaymentGateway interface using Stripe in stripe.go. Ensure all methods return mapped domain errors, not raw stripe errors."
// Go Interface Contract:
type PaymentGateway interface {
Charge(ctx context.Context, amount int64) (string, error)
Refund(ctx context.Context, transactionID string) error
}
2. Test-Driven Generation (TDG)
For the 2 Test-Driven Generation TDG stage, define the inputs, the owner of the step, and the exit criteria before changing code. Operators should be able to re-run the step from a known checkpoint without guessing hidden state. Record timings and token or query cost next to functional results. Cost visibility early prevents surprise bills when the path moves from demo to shared environments. Put human approval on edges that spend money or change production data. Compile-time wiring does not equal business completeness.
# Terminal Command:
claude "Run `go test -v ./calc` and implement calculator.go to make these exact tests pass without changing the test assertions."
// Go Test File:
func TestCalculateDiscount(t *testing.T) {
result := CalculateDiscount(100, "VIP")
if result != 80 {
t.Errorf("Expected 80, got %d", result)
}
}
3. Context Enforcement via CLAUDE.md
For the 3 Context Enforcement via stage, define the inputs, the owner of the step, and the exit criteria before changing code. Operators should be able to re-run the step from a known checkpoint without guessing hidden state. Keep configuration outside application code. Environment files, secret stores, and feature flags belong in one place operators can audit without reading the whole graph. Put human approval on edges that spend money or change production data. Compile-time wiring does not equal business completeness. For the 3 Context Enforcement via stage, define the inputs, the owner of the step, and the exit criteria before changing code. Operators should be able to re-run the step from a known checkpoint without guessing hidden state. Prefer small, testable units over sprawling scripts. When a step fails, the failure should point at a single responsibility rather than a tangled pipeline.
# Excerpt from CLAUDE.md:
## Go Conventions
Rule: Every exported I/O or database method MUST accept `context.Context` as its first parameter and pass it to the underlying driver (e.g., using `QueryRowContext`).
4. Explicit Error Wrapping
When working through the 4 Explicit Error Wrapping stage, write down the contract first: required inputs, success signal, and what happens on partial failure. That checklist keeps later code changes honest. Treat this stage as a contract between inputs and validated outputs. Name the artifacts, define success checks, and refuse silent partial completion. Checkpoint after expensive steps. Resume should not re-bill the same LLM call when an operator retries a later node.
# Terminal Command:
claude "Refactor config.go. If os.Open fails, wrap the error with context using fmt.Errorf and the %w verb."
// Generated Go Code:
file, err := os.Open("config.json")
if err != nil {
return fmt.Errorf("failed to open config file: %w", err)
}
5. Concurrency Scaffolding
When working through the 5 Concurrency Scaffolding stage, write down the contract first: required inputs, success signal, and what happens on partial failure. That checklist keeps later code changes honest. Record timings and token or query cost next to functional results. Cost visibility early prevents surprise bills when the path moves from demo to shared environments. Checkpoint after expensive steps. Resume should not re-bill the same LLM call when an operator retries a later node.
# Terminal Command:
claude "Implement a worker pool for the Job slice in worker.go. Use a buffered channel of size 5 and a sync.WaitGroup. Ensure the WaitGroup is closed cleanly."
// Go Code Scaffold:
jobs := make(chan Job, 5)
var wg sync.WaitGroup
// Claude generates the exact worker loop here based on the constraints
6. Type-Driven Development
When working through the 6 Type-Driven Development stage, write down the contract first: required inputs, success signal, and what happens on partial failure. That checklist keeps later code changes honest. Keep configuration outside application code. Environment files, secret stores, and feature flags belong in one place operators can audit without reading the whole graph. Checkpoint after expensive steps. Resume should not re-bill the same LLM call when an operator retries a later node. When working through the 6 Type-Driven Development stage, write down the contract first: required inputs, success signal, and what happens on partial failure. That checklist keeps later code changes honest. Prefer small, testable units over sprawling scripts. When a step fails, the failure should point at a single responsibility rather than a tangled pipeline.
# Terminal Command:
claude "Refactor the User struct. Change all string IDs to a custom type UserID string, and ensure all functions accepting an ID use this new type."
// Generated Go Code:
type UserID string
type User struct {
ID UserID
Email string
}
7. Dependency Injection Directives
The 7 Dependency Injection Directives stage works best when treated as a measurable surface. Capture one golden transcript, one failure case, and the rollback note before expanding scope. Treat this stage as a contract between inputs and validated outputs. Name the artifacts, define success checks, and refuse silent partial completion. Keep graph state flat and typed. Nested blobs hide which node wrote which field and break resume after interrupts.
# Terminal Command:
claude "Rewrite NewOrderService. Do not initialize the logger inside. Pass a *zap.Logger and a PaymentGateway interface as dependencies."
// Generated Go Code:
func NewOrderService(logger *zap.Logger, gateway PaymentGateway) *OrderService {
return &OrderService{
logger: logger,
gateway: gateway,
}
}
8. ⏱ Benchmark-Led Tuning
The 8 Benchmark-Led Tuning stage works best when treated as a measurable surface. Capture one golden transcript, one failure case, and the rollback note before expanding scope. Record timings and token or query cost next to functional results. Cost visibility early prevents surprise bills when the path moves from demo to shared environments. Keep graph state flat and typed. Nested blobs hide which node wrote which field and break resume after interrupts.
# Terminal command piping benchmark results directly to Claude Code:
go test -bench . -benchmem | claude "Our allocs/op is too high in the parser. Rewrite the parse function to use a sync.Pool for the byte slices."
// Generated Go Code:
var bufferPool = sync.Pool{
New: func() any {
b := make([]byte, 1024)
return &b
},
}
9. Iterative Struct Tagging
The 9 Iterative Struct Tagging stage works best when treated as a measurable surface. Capture one golden transcript, one failure case, and the rollback note before expanding scope. Keep configuration outside application code. Environment files, secret stores, and feature flags belong in one place operators can audit without reading the whole graph. Keep graph state flat and typed. Nested blobs hide which node wrote which field and break resume after interrupts. The 9 Iterative Struct Tagging stage works best when treated as a measurable surface. Capture one golden transcript, one failure case, and the rollback note before expanding scope. Prefer small, testable units over sprawling scripts. When a step fails, the failure should point at a single responsibility rather than a tangled pipeline.
# Terminal Command:
claude "Create a Go struct from this JSON payload. Add `json` tags, and include `validate` tags ensuring the email is valid and the age is >= 18."
// Generated Go Code:
type RegistrationRequest struct {
Email string `json:"email" validate:"required,email"`
Age int `json:"age" validate:"gte=18"`
}
10. Idiomatic GoDoc Prompting
For the 10 Idiomatic GoDoc Prompting stage, define the inputs, the owner of the step, and the exit criteria before changing code. Operators should be able to re-run the step from a known checkpoint without guessing hidden state. Treat this stage as a contract between inputs and validated outputs. Name the artifacts, define success checks, and refuse silent partial completion. Prefer structured outputs with schema validation over free-form prose when the next step is code or a tool call.
# Terminal Command:
claude "Add GoDoc comments to all exported types and functions in user_repo.go. Start the comment with the name of the identifier."
// Generated Go Code:
// UserRepository handles database operations for the User entity.
type UserRepository struct {
db *sql.DB
}
11. The Agentic Compile-Error Loop
For the 11 The Agentic Compile-Error stage, define the inputs, the owner of the step, and the exit criteria before changing code. Operators should be able to re-run the step from a known checkpoint without guessing hidden state. Record timings and token or query cost next to functional results. Cost visibility early prevents surprise bills when the path moves from demo to shared environments. Put human approval on edges that spend money or change production data. Compile-time wiring does not equal business completeness.
# Terminal Command:
claude "Run `go build ./...`. If it fails with type conversion errors, fix the casts in handler.go and retry until it compiles cleanly."
// Claude correctly casts the primitive to the custom type to fix the build:
userID := UserID(user.ID)
err := repo.GetByID(ctx, userID)
12. Architectural Boundary Enforcement (Plan Mode)
For the 12 Architectural Boundary Enforcement stage, define the inputs, the owner of the step, and the exit criteria before changing code. Operators should be able to re-run the step from a known checkpoint without guessing hidden state. Keep configuration outside application code. Environment files, secret stores, and feature flags belong in one place operators can audit without reading the whole graph. Put human approval on edges that spend money or change production data. Compile-time wiring does not equal business completeness. For the 12 Architectural Boundary Enforcement stage, define the inputs, the owner of the step, and the exit criteria before changing code. Operators should be able to re-run the step from a known checkpoint without guessing hidden state. Prefer small, testable units over sprawling scripts. When a step fails, the failure should point at a single responsibility rather than a tangled pipeline.
# Terminal Command:
claude "Create a new Order handler. Rule: Do not import the 'database/sql' package in this file. You may only interact with the database via the OrderUseCase interface. Use plan mode to show me the approach first."
// Generated Go Code:
func (h *OrderHandler) Create(w http.ResponseWriter, r *http.Request) {
// Claude generates clean HTTP handling without leaking DB logic here
}
So anyway, what pattern do you rely on the most when you pair with AI? Drop a comment below and let’s talk about how this crazy agentic stuff is evolving!
When working through the So anyway what pattern stage, write down the contract first: required inputs, success signal, and what happens on partial failure. That checklist keeps later code changes honest. Treat this stage as a contract between inputs and validated outputs. Name the artifacts, define success checks, and refuse silent partial completion. Checkpoint after expensive steps. Resume should not re-bill the same LLM call when an operator retries a later node.
Operational checklist
When working through the Operational checklist stage, write down the contract first: required inputs, success signal, and what happens on partial failure. That checklist keeps later code changes honest.
Document the happy path and the recovery path together. Retries, human gates, and dead-letter handling are part of the product, not later polish.
Checkpoint after expensive steps. Resume should not re-bill the same LLM call when an operator retries a later node.
Pin dependency versions and record the image digest that ran the demo. Reproducibility beats tribal knowledge.
Prefer small, testable units over sprawling scripts. When a step fails, the failure should point at a single responsibility rather than a tangled pipeline.
Checkpoint after expensive steps. Resume should not re-bill the same LLM call when an operator retries a later node.
Before promoting the stack, freeze versions, capture a golden transcript for the critical path, and confirm rollback steps. Shared environments need rate limits, tenancy checks, and a clear owner for secret rotation. Prefer boring reliability over clever one-off demos.
Batch note for 09e9b0c0b1cd: keep provider keys out of the repo, set a per-session token ceiling, and store transcripts next to the eval fixtures so later model swaps stay comparable.