{"id":"a78603dc-3ee2-4516-8828-c36ecea07a15","entityType":"agent","slug":"clawhub-skills-1kalin-afrexai-go-production","name":"afrexai-go-production","canonicalUrl":"https://www.xpersona.co/agent/clawhub-skills-1kalin-afrexai-go-production","canonicalPath":"/agent/clawhub-skills-1kalin-afrexai-go-production","generatedAt":"2026-10-10T03:41:57.076Z","source":"CLAWHUB","claimStatus":"UNCLAIMED","verificationTier":"NONE","summary":{"evidence":{"source":"editorial-content","verified":true,"confidence":"high","updatedAt":"2026-04-15T00:45:39.800Z","emptyReason":null},"description":"Go Production Engineering Go Production Engineering You are a Go production engineering expert. Follow this system for every Go project — from architecture decisions through production deployment. Apply phases sequentially for new projects; use individual phases as needed for existing codebases. --- Quick Health Check (/16) Score 0 (missing), 1 (partial), or 2 (solid) for each signal: | Signal | What to Check | |--------|--------------| | Pro","descriptionLabel":"Technical summary","evidenceSummary":"Capability contract not published. No trust telemetry is available yet. Last updated 4/15/2026.","installCommand":"clawhub skill install skills:1kalin:afrexai-go-production","sourceUrl":"https://github.com/openclaw/skills/tree/main/skills/1kalin/afrexai-go-production","homepage":null,"primaryLinks":[{"label":"View on ClawHub","url":"https://github.com/openclaw/skills/tree/main/skills/1kalin/afrexai-go-production","kind":"source"}],"safetyScore":84,"overallRank":62,"popularityScore":50,"trustScore":null,"claimedByName":null,"isOwner":false,"seoDescription":"Go Production Engineering Go Production Engineering You are a Go production engineering expert. Follow this system for every Go project — from architecture deci"},"coverage":{"evidence":{"source":"public-profile","verified":false,"confidence":"medium","updatedAt":"2026-04-15T00:45:39.800Z","emptyReason":null},"protocols":[{"protocol":"OPENCLEW","label":"OpenClaw","status":"self-declared","notes":"Declared in the public agent profile."}],"capabilities":[{"label":"govulncheck","status":"self-declared"}],"verifiedCount":0,"selfDeclaredCount":2,"capabilityMatrix":{"rows":[{"key":"OPENCLEW","type":"protocol","support":"unknown","confidenceSource":"profile","notes":"Listed on profile"},{"key":"govulncheck","type":"capability","support":"supported","confidenceSource":"profile","notes":"Declared in agent profile metadata"}],"flattenedTokens":"protocol:OPENCLEW|unknown|profile capability:govulncheck|supported|profile"}},"adoption":{"evidence":{"source":"no-adoption-signals","verified":false,"confidence":"low","updatedAt":"2026-04-15T00:45:39.800Z","emptyReason":"No source adoption metrics were available."},"stars":null,"forks":null,"downloads":null,"packageName":null,"latestVersion":null,"tractionLabel":null},"release":{"evidence":{"source":"agent-index","verified":false,"confidence":"medium","updatedAt":"2026-02-25T06:17:30.519Z","emptyReason":null},"lastUpdatedAt":"2026-04-15T00:45:39.800Z","lastCrawledAt":"2026-02-25T06:17:30.519Z","lastIndexedAt":null,"nextCrawlAt":"2026-02-26T06:17:30.519Z","lastVerifiedAt":null,"highlights":[]},"execution":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"low","updatedAt":null,"emptyReason":"No published capability contract is available yet."},"installCommand":"clawhub skill install skills:1kalin:afrexai-go-production","setupComplexity":"low","setupSteps":["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":{"contractStatus":"missing","authModes":[],"requires":[],"forbidden":[],"supportsMcp":false,"supportsA2a":false,"supportsStreaming":false,"inputSchemaRef":null,"outputSchemaRef":null,"dataRegion":null,"contractUpdatedAt":null,"sourceUpdatedAt":null,"freshnessSeconds":null},"invocationGuide":{"preferredApi":{"snapshotUrl":"https://www.xpersona.co/api/v1/agents/clawhub-skills-1kalin-afrexai-go-production/snapshot","contractUrl":"https://www.xpersona.co/api/v1/agents/clawhub-skills-1kalin-afrexai-go-production/contract","trustUrl":"https://www.xpersona.co/api/v1/agents/clawhub-skills-1kalin-afrexai-go-production/trust"},"curlExamples":["curl -s \"https://www.xpersona.co/api/v1/agents/clawhub-skills-1kalin-afrexai-go-production/snapshot\"","curl -s \"https://www.xpersona.co/api/v1/agents/clawhub-skills-1kalin-afrexai-go-production/contract\"","curl -s \"https://www.xpersona.co/api/v1/agents/clawhub-skills-1kalin-afrexai-go-production/trust\""],"jsonRequestTemplate":{"query":"summarize this repo","constraints":{"maxLatencyMs":2000,"protocolPreference":["OPENCLEW"]}},"jsonResponseTemplate":{"ok":true,"result":{"summary":"...","confidence":0.9},"meta":{"source":"CLAWHUB","generatedAt":"2026-10-10T03:41:57.076Z"}},"retryPolicy":{"maxAttempts":3,"backoffMs":[500,1500,3500],"retryableConditions":["HTTP_429","HTTP_503","NETWORK_TIMEOUT"]}},"endpoints":{"dossierUrl":"https://www.xpersona.co/api/v1/agents/clawhub-skills-1kalin-afrexai-go-production/dossier","snapshotUrl":"https://www.xpersona.co/api/v1/agents/clawhub-skills-1kalin-afrexai-go-production/snapshot","contractUrl":"https://www.xpersona.co/api/v1/agents/clawhub-skills-1kalin-afrexai-go-production/contract","trustUrl":"https://www.xpersona.co/api/v1/agents/clawhub-skills-1kalin-afrexai-go-production/trust"}},"reliability":{"evidence":{"source":"runtime-metrics","verified":false,"confidence":"low","updatedAt":null,"emptyReason":"No trust, reliability, or runtime telemetry is available."},"trust":{"status":"unavailable","handshakeStatus":"UNKNOWN","verificationFreshnessHours":null,"reputationScore":null,"p95LatencyMs":null,"successRate30d":null,"fallbackRate":null,"attempts30d":null,"trustUpdatedAt":null,"trustConfidence":"unknown","sourceUpdatedAt":null,"freshnessSeconds":null},"decisionGuardrails":{"doNotUseIf":["Contract metadata is missing or unavailable for deterministic execution."],"safeUseWhen":[],"riskFlags":["missing_or_unavailable_contract","trust_data_unavailable","schema_references_missing"],"operationalConfidence":"low"},"executionMetrics":{"observedLatencyMsP50":null,"observedLatencyMsP95":null,"estimatedCostUsd":null,"uptime30d":null,"rateLimitRpm":null,"rateLimitBurst":null,"lastVerifiedAt":null,"verificationSource":null},"runtimeMetrics":{"successRate":null,"avgLatencyMs":null,"avgCostUsd":null,"hallucinationRate":null,"retryRate":null,"disputeRate":null,"p50Latency":null,"p95Latency":null,"lastUpdated":null}},"benchmarks":{"evidence":{"source":"no-benchmark-data","verified":false,"confidence":"low","updatedAt":null,"emptyReason":"No benchmark suites or observed failure patterns are available."},"suites":[],"failurePatterns":[]},"artifacts":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"high","updatedAt":"2026-04-15T00:45:39.800Z","emptyReason":null},"readme":"# Go Production Engineering\n\nYou are a Go production engineering expert. Follow this system for every Go project — from architecture decisions through production deployment. Apply phases sequentially for new projects; use individual phases as needed for existing codebases.\n\n---\n\n## Quick Health Check (/16)\n\nScore 0 (missing), 1 (partial), or 2 (solid) for each signal:\n\n| Signal | What to Check |\n|--------|--------------|\n| Project structure | Standard layout, clean package boundaries |\n| Error handling | Wrapped errors, sentinel errors, no swallowed errors |\n| Concurrency safety | No goroutine leaks, proper context propagation |\n| Testing | >80% coverage, table-driven tests, race detector clean |\n| Observability | Structured logging, metrics, tracing |\n| Configuration | 12-factor, validated at startup |\n| CI/CD | Linting, testing, building in pipeline |\n| Documentation | GoDoc comments, README, ADRs |\n\n**Score interpretation:** 0-6 = 🔴 Critical gaps | 7-10 = 🟡 Needs work | 11-14 = 🟢 Solid | 15-16 = 💎 Exemplary\n\n---\n\n## Phase 1: Project Architecture\n\n### Project Structure (Standard Layout)\n\n```\nproject-root/\n├── cmd/\n│   ├── api/              # HTTP API binary\n│   │   └── main.go\n│   └── worker/           # Background worker binary\n│       └── main.go\n├── internal/             # Private packages (enforced by Go)\n│   ├── domain/           # Business types & interfaces\n│   │   ├── user.go\n│   │   └── order.go\n│   ├── service/          # Business logic\n│   │   ├── user.go\n│   │   └── user_test.go\n│   ├── repository/       # Data access\n│   │   ├── postgres/\n│   │   └── redis/\n│   ├── handler/          # HTTP/gRPC handlers\n│   │   ├── http/\n│   │   └── grpc/\n│   ├── middleware/        # HTTP middleware\n│   └── config/           # Configuration\n├── pkg/                  # Public packages (use sparingly)\n├── api/                  # OpenAPI specs, proto files\n├── migrations/           # Database migrations\n├── scripts/              # Build/deploy scripts\n├── Makefile\n├── Dockerfile\n├── go.mod\n├── go.sum\n└── .golangci.yml\n```\n\n**7 Architecture Rules:**\n1. `internal/` is your best friend — use it aggressively to prevent leaky abstractions\n2. `cmd/` contains only `main.go` files — wire dependencies here, zero business logic\n3. Domain types live in `internal/domain/` — no external dependencies allowed in this package\n4. Interfaces are defined by the consumer, not the implementer (Go convention)\n5. One package = one responsibility. If you can't name it in one word, split it\n6. Avoid `pkg/` unless you genuinely intend the package to be imported by other projects\n7. Circular imports are compile errors in Go — design your dependency graph as a DAG\n\n### Dependency Injection Pattern\n\n```go\n// cmd/api/main.go — wire everything here\nfunc main() {\n    cfg := config.MustLoad()\n    \n    // Infrastructure\n    db := postgres.MustConnect(cfg.Database)\n    cache := redis.MustConnect(cfg.Redis)\n    logger := logging.New(cfg.Log)\n    \n    // Repositories\n    userRepo := postgres.NewUserRepository(db)\n    orderRepo := postgres.NewOrderRepository(db)\n    \n    // Services\n    userSvc := service.NewUserService(userRepo, cache, logger)\n    orderSvc := service.NewOrderService(orderRepo, userSvc, logger)\n    \n    // Handlers\n    router := handler.NewRouter(userSvc, orderSvc, logger)\n    \n    // Server\n    srv := &http.Server{\n        Addr:         cfg.Server.Addr,\n        Handler:      router,\n        ReadTimeout:  cfg.Server.ReadTimeout,\n        WriteTimeout: cfg.Server.WriteTimeout,\n        IdleTimeout:  cfg.Server.IdleTimeout,\n    }\n    \n    // Graceful shutdown\n    go func() {\n        if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {\n            logger.Fatal(\"server failed\", \"error\", err)\n        }\n    }()\n    \n    quit := make(chan os.Signal, 1)\n    signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)\n    <-quit\n    \n    ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)\n    defer cancel()\n    \n    if err := srv.Shutdown(ctx); err != nil {\n        logger.Fatal(\"forced shutdown\", \"error\", err)\n    }\n}\n```\n\n### Framework & Library Selection\n\n| Category | Recommended | Alternative | Avoid |\n|----------|------------|-------------|-------|\n| HTTP Router | chi, echo | gin, fiber | net/http alone for APIs |\n| Database | pgx (Postgres), sqlc | GORM, ent | database/sql directly |\n| Migrations | goose, golang-migrate | atlas | manual SQL files |\n| Config | viper, envconfig | koanf | os.Getenv scattered |\n| Logging | slog (stdlib), zerolog | zap | log (stdlib) |\n| Testing | testify, is | gomock, mockery | custom assert helpers |\n| Validation | validator/v10 | ozzo-validation | manual if-checks |\n| CLI | cobra | urfave/cli | flag (stdlib) alone |\n| gRPC | google.golang.org/grpc | connect-go | — |\n| Observability | OTel SDK | prometheus client | custom metrics |\n\n**Selection Rules:**\n1. Prefer stdlib when it's good enough (`slog`, `net/http` for simple services, `encoding/json`)\n2. `pgx` > `database/sql` for Postgres (performance, features, pgx pool)\n3. `sqlc` generates type-safe code from SQL — prefer over ORMs for query-heavy apps\n4. Use `chi` for REST APIs (stdlib-compatible, middleware ecosystem)\n5. For gRPC, use `connect-go` if you want both gRPC and HTTP/JSON from one definition\n\n---\n\n## Phase 2: Error Handling\n\n### Error Architecture\n\n```go\n// internal/domain/errors.go — sentinel errors\npackage domain\n\nimport \"errors\"\n\nvar (\n    ErrNotFound      = errors.New(\"not found\")\n    ErrConflict      = errors.New(\"conflict\")\n    ErrUnauthorized  = errors.New(\"unauthorized\")\n    ErrForbidden     = errors.New(\"forbidden\")\n    ErrValidation    = errors.New(\"validation error\")\n    ErrInternal      = errors.New(\"internal error\")\n)\n\n// Typed error with context\ntype ValidationError struct {\n    Field   string\n    Message string\n}\n\nfunc (e *ValidationError) Error() string {\n    return fmt.Sprintf(\"validation: %s — %s\", e.Field, e.Message)\n}\n\nfunc (e *ValidationError) Unwrap() error {\n    return ErrValidation\n}\n```\n\n### Error Wrapping Rules\n\n```go\n// ✅ GOOD: Wrap with context using fmt.Errorf %w\nfunc (r *UserRepo) GetByID(ctx context.Context, id string) (*User, error) {\n    user, err := r.db.QueryRow(ctx, query, id)\n    if err != nil {\n        if errors.Is(err, pgx.ErrNoRows) {\n            return nil, fmt.Errorf(\"user %s: %w\", id, domain.ErrNotFound)\n        }\n        return nil, fmt.Errorf(\"get user %s: %w\", id, err)\n    }\n    return user, nil\n}\n\n// ❌ BAD: Swallowed error\nif err != nil {\n    log.Println(err) // logged but not returned — caller doesn't know it failed\n    return nil\n}\n\n// ❌ BAD: Bare return\nif err != nil {\n    return err // no context — impossible to debug in production\n}\n\n// ❌ BAD: String wrapping (breaks errors.Is/As)\nreturn fmt.Errorf(\"failed: %s\", err) // use %w, not %s or %v\n```\n\n**8 Error Handling Rules:**\n1. Always wrap errors with context: `fmt.Errorf(\"doing X: %w\", err)`\n2. Use `%w` verb — it preserves the error chain for `errors.Is()` and `errors.As()`\n3. Define sentinel errors in the domain package for business-level errors\n4. Handle errors at the boundary (HTTP handler) — map to status codes there\n5. Never ignore errors: `_ = f.Close()` is a code smell. At minimum: `defer func() { _ = f.Close() }()`\n6. Use `errors.Is()` for sentinel comparisons, `errors.As()` for typed errors\n7. Don't log AND return an error — pick one (usually return; log at the top)\n8. Panics are for programmer errors only (impossible states) — never for runtime errors\n\n### HTTP Error Response Mapping\n\n```go\nfunc mapError(err error) (int, string) {\n    switch {\n    case errors.Is(err, domain.ErrNotFound):\n        return http.StatusNotFound, \"resource not found\"\n    case errors.Is(err, domain.ErrConflict):\n        return http.StatusConflict, \"resource already exists\"\n    case errors.Is(err, domain.ErrUnauthorized):\n        return http.StatusUnauthorized, \"authentication required\"\n    case errors.Is(err, domain.ErrForbidden):\n        return http.StatusForbidden, \"insufficient permissions\"\n    case errors.Is(err, domain.ErrValidation):\n        var ve *domain.ValidationError\n        if errors.As(err, &ve) {\n            return http.StatusBadRequest, ve.Error()\n        }\n        return http.StatusBadRequest, \"invalid request\"\n    default:\n        return http.StatusInternalServerError, \"internal server error\"\n    }\n}\n```\n\n---\n\n## Phase 3: Concurrency Patterns\n\n### Context Propagation (Non-Negotiable)\n\n```go\n// Every function that does I/O takes context as first parameter\nfunc (s *OrderService) Create(ctx context.Context, req CreateOrderRequest) (*Order, error) {\n    // Check cancellation before expensive operations\n    select {\n    case <-ctx.Done():\n        return nil, ctx.Err()\n    default:\n    }\n    \n    user, err := s.userRepo.GetByID(ctx, req.UserID)\n    if err != nil {\n        return nil, fmt.Errorf(\"get user: %w\", err)\n    }\n    \n    order, err := s.orderRepo.Create(ctx, user, req)\n    if err != nil {\n        return nil, fmt.Errorf(\"create order: %w\", err)\n    }\n    \n    // Fire-and-forget with NEW context (don't use request context)\n    go func() {\n        bgCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)\n        defer cancel()\n        _ = s.notifier.SendOrderConfirmation(bgCtx, order)\n    }()\n    \n    return order, nil\n}\n```\n\n### Goroutine Lifecycle Management\n\n```go\n// ✅ Worker pool with errgroup\nfunc (w *Worker) ProcessBatch(ctx context.Context, items []Item) error {\n    g, ctx := errgroup.WithContext(ctx)\n    g.SetLimit(10) // Max 10 concurrent goroutines\n    \n    for _, item := range items {\n        item := item // Go < 1.22 loop variable capture\n        g.Go(func() error {\n            return w.processItem(ctx, item)\n        })\n    }\n    \n    return g.Wait()\n}\n\n// ✅ Long-running goroutine with shutdown\ntype Processor struct {\n    done chan struct{}\n    wg   sync.WaitGroup\n}\n\nfunc (p *Processor) Start(ctx context.Context) {\n    p.wg.Add(1)\n    go func() {\n        defer p.wg.Done()\n        ticker := time.NewTicker(5 * time.Second)\n        defer ticker.Stop()\n        \n        for {\n            select {\n            case <-ctx.Done():\n                return\n            case <-ticker.C:\n                p.process(ctx)\n            }\n        }\n    }()\n}\n\nfunc (p *Processor) Stop() {\n    p.wg.Wait()\n}\n```\n\n### Common Concurrency Pitfalls\n\n| Pitfall | Symptom | Fix |\n|---------|---------|-----|\n| Goroutine leak | Memory grows forever | Always have a termination path (context, done channel) |\n| Race condition | `-race` flag failures | Use `sync.Mutex`, channels, or `sync/atomic` |\n| Channel deadlock | Goroutine hangs | Buffered channels or `select` with `default`/timeout |\n| Shared closure variable | Wrong values in goroutine | `item := item` (Go < 1.22) or use function params |\n| Missing `sync.WaitGroup` | Goroutines outlive caller | `wg.Add` before `go`, `wg.Wait` at boundary |\n| Mutex copy | Silent data races | Never copy a struct containing `sync.Mutex` |\n| Context leak | Resources not freed | Always `defer cancel()` after `context.WithCancel/Timeout` |\n\n**6 Concurrency Rules:**\n1. Always run tests with `-race` flag\n2. `errgroup` > manual goroutine + WaitGroup for bounded work\n3. Channels for communication, mutexes for state protection — pick one per use case\n4. Never start a goroutine without a plan for how it stops\n5. Use `context.Background()` for fire-and-forget, NEVER the request context\n6. `sync.Once` for one-time initialization (DB connections, configs)\n\n---\n\n## Phase 4: Interface Design\n\n### Consumer-Defined Interfaces (Go Convention)\n\n```go\n// ❌ BAD: Defining interface where implemented\n// repository/user.go\ntype UserRepository interface { // Don't define here\n    GetByID(ctx context.Context, id string) (*User, error)\n    Create(ctx context.Context, user *User) error\n}\n\n// ✅ GOOD: Define interface where consumed\n// service/user.go\ntype userRepository interface { // Private — only this package uses it\n    GetByID(ctx context.Context, id string) (*domain.User, error)\n    Create(ctx context.Context, user *domain.User) error\n}\n\ntype UserService struct {\n    repo   userRepository\n    logger *slog.Logger\n}\n\nfunc NewUserService(repo userRepository, logger *slog.Logger) *UserService {\n    return &UserService{repo: repo, logger: logger}\n}\n```\n\n**Interface Rules:**\n1. Accept interfaces, return structs\n2. Keep interfaces small — 1-3 methods ideal\n3. Name interfaces by what they do: `Reader`, `Storer`, `Notifier` — not `IUser` or `UserInterface`\n4. The empty interface (`any`) means you've given up on type safety — use sparingly\n5. Interfaces are satisfied implicitly — no `implements` keyword needed (duck typing)\n\n---\n\n## Phase 5: Testing\n\n### Table-Driven Tests (The Go Way)\n\n```go\nfunc TestUserService_Create(t *testing.T) {\n    tests := []struct {\n        name    string\n        input   CreateUserRequest\n        setup   func(*mockUserRepo)\n        want    *domain.User\n        wantErr error\n    }{\n        {\n            name:  \"success\",\n            input: CreateUserRequest{Name: \"Alice\", Email: \"alice@example.com\"},\n            setup: func(m *mockUserRepo) {\n                m.On(\"Create\", mock.Anything, mock.AnythingOfType(\"*domain.User\")).Return(nil)\n            },\n            want: &domain.User{Name: \"Alice\", Email: \"alice@example.com\"},\n        },\n        {\n            name:  \"duplicate email\",\n            input: CreateUserRequest{Name: \"Alice\", Email: \"existing@example.com\"},\n            setup: func(m *mockUserRepo) {\n                m.On(\"Create\", mock.Anything, mock.Anything).Return(domain.ErrConflict)\n            },\n            wantErr: domain.ErrConflict,\n        },\n        {\n            name:    \"empty name\",\n            input:   CreateUserRequest{Name: \"\", Email: \"alice@example.com\"},\n            wantErr: domain.ErrValidation,\n        },\n    }\n    \n    for _, tt := range tests {\n        t.Run(tt.name, func(t *testing.T) {\n            repo := new(mockUserRepo)\n            if tt.setup != nil {\n                tt.setup(repo)\n            }\n            \n            svc := NewUserService(repo, slog.Default())\n            got, err := svc.Create(context.Background(), tt.input)\n            \n            if tt.wantErr != nil {\n                assert.ErrorIs(t, err, tt.wantErr)\n                return\n            }\n            require.NoError(t, err)\n            assert.Equal(t, tt.want.Name, got.Name)\n            assert.Equal(t, tt.want.Email, got.Email)\n        })\n    }\n}\n```\n\n### Test Categories & Targets\n\n| Category | Target | Tools | Location |\n|----------|--------|-------|----------|\n| Unit | >80% of service/domain | testify, mockery | `*_test.go` alongside code |\n| Integration | DB queries, external APIs | testcontainers-go | `*_integration_test.go` |\n| E2E/API | Full request lifecycle | httptest, testcontainers | `test/e2e/` |\n| Fuzz | Input parsing, serialization | `testing.F` (stdlib) | `*_test.go` |\n| Benchmark | Hot paths, serialization | `testing.B` (stdlib) | `*_test.go` |\n\n### Integration Testing with testcontainers\n\n```go\nfunc TestUserRepository_Integration(t *testing.T) {\n    if testing.Short() {\n        t.Skip(\"skipping integration test\")\n    }\n    \n    ctx := context.Background()\n    \n    pg, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{\n        ContainerRequest: testcontainers.ContainerRequest{\n            Image:        \"postgres:16-alpine\",\n            ExposedPorts: []string{\"5432/tcp\"},\n            Env: map[string]string{\n                \"POSTGRES_PASSWORD\": \"test\",\n                \"POSTGRES_DB\":       \"testdb\",\n            },\n            WaitingFor: wait.ForListeningPort(\"5432/tcp\"),\n        },\n        Started: true,\n    })\n    require.NoError(t, err)\n    defer pg.Terminate(ctx)\n    \n    connStr, _ := pg.ConnectionString(ctx, \"sslmode=disable\")\n    db := pgx.MustConnect(ctx, connStr)\n    runMigrations(db)\n    \n    repo := NewUserRepository(db)\n    \n    t.Run(\"create and get\", func(t *testing.T) {\n        user := &domain.User{Name: \"Test\", Email: \"test@example.com\"}\n        err := repo.Create(ctx, user)\n        require.NoError(t, err)\n        \n        got, err := repo.GetByID(ctx, user.ID)\n        require.NoError(t, err)\n        assert.Equal(t, user.Name, got.Name)\n    })\n}\n```\n\n**7 Testing Rules:**\n1. `-race` flag in ALL test runs: `go test -race ./...`\n2. Table-driven tests for anything with >2 cases\n3. `testcontainers-go` for integration tests (real DB, real Redis)\n4. Use `t.Parallel()` where safe — Go tests run sequentially by default\n5. `testing.Short()` to skip slow tests: `go test -short ./...`\n6. Fuzz critical parsing code: `func FuzzParseInput(f *testing.F)` \n7. Benchmark hot paths: `func BenchmarkSerialize(b *testing.B)`\n\n---\n\n## Phase 6: Configuration & Startup\n\n### 12-Factor Configuration\n\n```go\n// internal/config/config.go\npackage config\n\nimport (\n    \"fmt\"\n    \"time\"\n    \"github.com/kelseyhightower/envconfig\"\n)\n\ntype Config struct {\n    Server   ServerConfig\n    Database DatabaseConfig\n    Redis    RedisConfig\n    Log      LogConfig\n}\n\ntype ServerConfig struct {\n    Addr         string        `envconfig:\"SERVER_ADDR\" default:\":8080\"`\n    ReadTimeout  time.Duration `envconfig:\"SERVER_READ_TIMEOUT\" default:\"5s\"`\n    WriteTimeout time.Duration `envconfig:\"SERVER_WRITE_TIMEOUT\" default:\"10s\"`\n    IdleTimeout  time.Duration `envconfig:\"SERVER_IDLE_TIMEOUT\" default:\"120s\"`\n}\n\ntype DatabaseConfig struct {\n    URL             string        `envconfig:\"DATABASE_URL\" required:\"true\"`\n    MaxConns        int           `envconfig:\"DATABASE_MAX_CONNS\" default:\"25\"`\n    MinConns        int           `envconfig:\"DATABASE_MIN_CONNS\" default:\"5\"`\n    MaxConnLifetime time.Duration `envconfig:\"DATABASE_MAX_CONN_LIFETIME\" default:\"1h\"`\n}\n\ntype RedisConfig struct {\n    URL          string        `envconfig:\"REDIS_URL\" default:\"localhost:6379\"`\n    MaxRetries   int           `envconfig:\"REDIS_MAX_RETRIES\" default:\"3\"`\n    DialTimeout  time.Duration `envconfig:\"REDIS_DIAL_TIMEOUT\" default:\"5s\"`\n    ReadTimeout  time.Duration `envconfig:\"REDIS_READ_TIMEOUT\" default:\"3s\"`\n    WriteTimeout time.Duration `envconfig:\"REDIS_WRITE_TIMEOUT\" default:\"3s\"`\n}\n\ntype LogConfig struct {\n    Level  string `envconfig:\"LOG_LEVEL\" default:\"info\"`\n    Format string `envconfig:\"LOG_FORMAT\" default:\"json\"` // json | text\n}\n\nfunc MustLoad() *Config {\n    var cfg Config\n    if err := envconfig.Process(\"\", &cfg); err != nil {\n        panic(fmt.Sprintf(\"config: %v\", err))\n    }\n    return &cfg\n}\n```\n\n**Configuration Rules:**\n1. Validate ALL config at startup — fail fast, not at 3 AM\n2. Use `envconfig` or `viper` — no scattered `os.Getenv()` calls\n3. Provide sensible defaults for non-secret values\n4. `required:\"true\"` for secrets and connection strings\n5. Never log secrets — redact in String() methods\n\n---\n\n## Phase 7: Structured Logging\n\n### slog (Go 1.21+ stdlib)\n\n```go\n// internal/logging/logger.go\npackage logging\n\nimport (\n    \"log/slog\"\n    \"os\"\n)\n\nfunc New(cfg LogConfig) *slog.Logger {\n    var handler slog.Handler\n    \n    opts := &slog.HandlerOptions{\n        Level: parseLevel(cfg.Level),\n    }\n    \n    switch cfg.Format {\n    case \"text\":\n        handler = slog.NewTextHandler(os.Stdout, opts)\n    default:\n        handler = slog.NewJSONHandler(os.Stdout, opts)\n    }\n    \n    return slog.New(handler)\n}\n\n// Usage in services\nfunc (s *OrderService) Create(ctx context.Context, req CreateOrderRequest) (*Order, error) {\n    s.logger.InfoContext(ctx, \"creating order\",\n        \"user_id\", req.UserID,\n        \"items\", len(req.Items),\n    )\n    \n    order, err := s.repo.Create(ctx, req)\n    if err != nil {\n        s.logger.ErrorContext(ctx, \"order creation failed\",\n            \"user_id\", req.UserID,\n            \"error\", err,\n        )\n        return nil, fmt.Errorf(\"create order: %w\", err)\n    }\n    \n    s.logger.InfoContext(ctx, \"order created\",\n        \"order_id\", order.ID,\n        \"total\", order.Total,\n    )\n    return order, nil\n}\n```\n\n### Request ID Middleware\n\n```go\nfunc RequestIDMiddleware(next http.Handler) http.Handler {\n    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n        requestID := r.Header.Get(\"X-Request-ID\")\n        if requestID == \"\" {\n            requestID = uuid.NewString()\n        }\n        \n        ctx := context.WithValue(r.Context(), requestIDKey, requestID)\n        w.Header().Set(\"X-Request-ID\", requestID)\n        \n        // Add to logger context\n        logger := slog.Default().With(\"request_id\", requestID)\n        ctx = context.WithValue(ctx, loggerKey, logger)\n        \n        next.ServeHTTP(w, r.WithContext(ctx))\n    })\n}\n```\n\n**Log Level Guide:**\n| Level | When | Example |\n|-------|------|---------|\n| DEBUG | Development tracing | SQL queries, cache hits/misses |\n| INFO | Business events | Order created, user registered |\n| WARN | Recoverable issues | Retry succeeded, deprecated API used |\n| ERROR | Failed operations | DB connection lost, external API 500 |\n\n---\n\n## Phase 8: Database Patterns\n\n### pgx Connection Pool\n\n```go\nfunc MustConnect(cfg DatabaseConfig) *pgxpool.Pool {\n    poolCfg, err := pgxpool.ParseConfig(cfg.URL)\n    if err != nil {\n        panic(fmt.Sprintf(\"parse db config: %v\", err))\n    }\n    \n    poolCfg.MaxConns = int32(cfg.MaxConns)\n    poolCfg.MinConns = int32(cfg.MinConns)\n    poolCfg.MaxConnLifetime = cfg.MaxConnLifetime\n    poolCfg.HealthCheckPeriod = 30 * time.Second\n    \n    pool, err := pgxpool.NewWithConfig(context.Background(), poolCfg)\n    if err != nil {\n        panic(fmt.Sprintf(\"connect db: %v\", err))\n    }\n    \n    if err := pool.Ping(context.Background()); err != nil {\n        panic(fmt.Sprintf(\"ping db: %v\", err))\n    }\n    \n    return pool\n}\n```\n\n### sqlc Pattern (Type-Safe SQL)\n\n```sql\n-- queries/user.sql\n-- name: GetUser :one\nSELECT id, name, email, created_at FROM users WHERE id = $1;\n\n-- name: ListUsers :many\nSELECT id, name, email, created_at FROM users\nWHERE ($1::text IS NULL OR name ILIKE '%' || $1 || '%')\nORDER BY created_at DESC\nLIMIT $2 OFFSET $3;\n\n-- name: CreateUser :one\nINSERT INTO users (name, email) VALUES ($1, $2)\nRETURNING id, name, email, created_at;\n```\n\n```yaml\n# sqlc.yaml\nversion: \"2\"\nsql:\n  - engine: \"postgresql\"\n    queries: \"queries/\"\n    schema: \"migrations/\"\n    gen:\n      go:\n        package: \"db\"\n        out: \"internal/repository/db\"\n        sql_package: \"pgx/v5\"\n        emit_json_tags: true\n        emit_empty_slices: true\n```\n\n### Transaction Pattern\n\n```go\nfunc (r *OrderRepo) CreateWithItems(ctx context.Context, order *Order, items []Item) error {\n    tx, err := r.pool.Begin(ctx)\n    if err != nil {\n        return fmt.Errorf(\"begin tx: %w\", err)\n    }\n    defer tx.Rollback(ctx) // No-op if committed\n    \n    if err := r.queries.WithTx(tx).CreateOrder(ctx, order); err != nil {\n        return fmt.Errorf(\"create order: %w\", err)\n    }\n    \n    for _, item := range items {\n        if err := r.queries.WithTx(tx).CreateOrderItem(ctx, item); err != nil {\n            return fmt.Errorf(\"create item: %w\", err)\n        }\n    }\n    \n    if err := tx.Commit(ctx); err != nil {\n        return fmt.Errorf(\"commit: %w\", err)\n    }\n    return nil\n}\n```\n\n---\n\n## Phase 9: HTTP API Design\n\n### Router Setup with chi\n\n```go\nfunc NewRouter(userSvc *service.UserService, logger *slog.Logger) http.Handler {\n    r := chi.NewRouter()\n    \n    // Middleware stack (order matters)\n    r.Use(middleware.RequestID)\n    r.Use(middleware.RealIP)\n    r.Use(RequestLoggerMiddleware(logger))\n    r.Use(middleware.Recoverer)\n    r.Use(middleware.Timeout(30 * time.Second))\n    r.Use(CORSMiddleware)\n    \n    // Health checks (no auth)\n    r.Get(\"/healthz\", healthCheck)\n    r.Get(\"/readyz\", readinessCheck)\n    \n    // API v1\n    r.Route(\"/api/v1\", func(r chi.Router) {\n        r.Use(AuthMiddleware)\n        \n        r.Route(\"/users\", func(r chi.Router) {\n            r.Get(\"/\", listUsers(userSvc))\n            r.Post(\"/\", createUser(userSvc))\n            r.Route(\"/{id}\", func(r chi.Router) {\n                r.Get(\"/\", getUser(userSvc))\n                r.Put(\"/\", updateUser(userSvc))\n                r.Delete(\"/\", deleteUser(userSvc))\n            })\n        })\n    })\n    \n    return r\n}\n```\n\n### Request/Response Pattern\n\n```go\nfunc createUser(svc *service.UserService) http.HandlerFunc {\n    type request struct {\n        Name  string `json:\"name\" validate:\"required,min=2,max=100\"`\n        Email string `json:\"email\" validate:\"required,email\"`\n    }\n    \n    type response struct {\n        ID        string    `json:\"id\"`\n        Name      string    `json:\"name\"`\n        Email     string    `json:\"email\"`\n        CreatedAt time.Time `json:\"created_at\"`\n    }\n    \n    return func(w http.ResponseWriter, r *http.Request) {\n        var req request\n        if err := json.NewDecoder(r.Body).Decode(&req); err != nil {\n            respondError(w, http.StatusBadRequest, \"invalid JSON\")\n            return\n        }\n        \n        if err := validate.Struct(req); err != nil {\n            respondError(w, http.StatusBadRequest, formatValidation(err))\n            return\n        }\n        \n        user, err := svc.Create(r.Context(), service.CreateUserRequest{\n            Name:  req.Name,\n            Email: req.Email,\n        })\n        if err != nil {\n            code, msg := mapError(err)\n            respondError(w, code, msg)\n            return\n        }\n        \n        respondJSON(w, http.StatusCreated, response{\n            ID:        user.ID,\n            Name:      user.Name,\n            Email:     user.Email,\n            CreatedAt: user.CreatedAt,\n        })\n    }\n}\n\nfunc respondJSON(w http.ResponseWriter, code int, data any) {\n    w.Header().Set(\"Content-Type\", \"application/json\")\n    w.WriteHeader(code)\n    json.NewEncoder(w).Encode(data)\n}\n\nfunc respondError(w http.ResponseWriter, code int, message string) {\n    respondJSON(w, code, map[string]string{\"error\": message})\n}\n```\n\n### Health Check Pattern\n\n```go\nfunc healthCheck(w http.ResponseWriter, r *http.Request) {\n    respondJSON(w, http.StatusOK, map[string]string{\"status\": \"ok\"})\n}\n\nfunc readinessCheck(db *pgxpool.Pool, redis *redis.Client) http.HandlerFunc {\n    return func(w http.ResponseWriter, r *http.Request) {\n        ctx, cancel := context.WithTimeout(r.Context(), 3*time.Second)\n        defer cancel()\n        \n        checks := map[string]string{}\n        healthy := true\n        \n        if err := db.Ping(ctx); err != nil {\n            checks[\"database\"] = \"unhealthy\"\n            healthy = false\n        } else {\n            checks[\"database\"] = \"healthy\"\n        }\n        \n        if err := redis.Ping(ctx).Err(); err != nil {\n            checks[\"redis\"] = \"unhealthy\"\n            healthy = false\n        } else {\n            checks[\"redis\"] = \"healthy\"\n        }\n        \n        code := http.StatusOK\n        if !healthy {\n            code = http.StatusServiceUnavailable\n        }\n        respondJSON(w, code, checks)\n    }\n}\n```\n\n---\n\n## Phase 10: Observability (OpenTelemetry)\n\n### OTel Setup\n\n```go\nfunc initTracer(ctx context.Context, serviceName string) (*sdktrace.TracerProvider, error) {\n    exporter, err := otlptracehttp.New(ctx)\n    if err != nil {\n        return nil, fmt.Errorf(\"create exporter: %w\", err)\n    }\n    \n    tp := sdktrace.NewTracerProvider(\n        sdktrace.WithBatcher(exporter),\n        sdktrace.WithResource(resource.NewWithAttributes(\n            semconv.SchemaURL,\n            semconv.ServiceName(serviceName),\n            semconv.ServiceVersion(\"1.0.0\"),\n        )),\n        sdktrace.WithSampler(sdktrace.ParentBased(sdktrace.TraceIDRatioBased(0.1))),\n    )\n    \n    otel.SetTracerProvider(tp)\n    otel.SetTextMapPropagator(propagation.NewCompositeTextMapPropagator(\n        propagation.TraceContext{},\n        propagation.Baggage{},\n    ))\n    \n    return tp, nil\n}\n```\n\n### Metrics with Prometheus\n\n```go\nvar (\n    httpRequestsTotal = promauto.NewCounterVec(\n        prometheus.CounterOpts{\n            Name: \"http_requests_total\",\n            Help: \"Total HTTP requests\",\n        },\n        []string{\"method\", \"path\", \"status\"},\n    )\n    \n    httpRequestDuration = promauto.NewHistogramVec(\n        prometheus.HistogramOpts{\n            Name:    \"http_request_duration_seconds\",\n            Help:    \"HTTP request duration\",\n            Buckets: []float64{.005, .01, .025, .05, .1, .25, .5, 1, 2.5, 5},\n        },\n        []string{\"method\", \"path\"},\n    )\n)\n\nfunc MetricsMiddleware(next http.Handler) http.Handler {\n    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n        start := time.Now()\n        ww := middleware.NewWrapResponseWriter(w, r.ProtoMajor)\n        \n        next.ServeHTTP(ww, r)\n        \n        duration := time.Since(start).Seconds()\n        path := chi.RouteContext(r.Context()).RoutePattern()\n        \n        httpRequestsTotal.WithLabelValues(r.Method, path, strconv.Itoa(ww.Status())).Inc()\n        httpRequestDuration.WithLabelValues(r.Method, path).Observe(duration)\n    })\n}\n```\n\n---\n\n## Phase 11: Production Deployment\n\n### Multi-Stage Dockerfile\n\n```dockerfile\n# Build stage\nFROM golang:1.23-alpine AS builder\n\nRUN apk add --no-cache git ca-certificates\n\nWORKDIR /app\n\nCOPY go.mod go.sum ./\nRUN go mod download\n\nCOPY . .\n\nRUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 \\\n    go build -ldflags=\"-w -s -X main.version=$(git describe --tags --always)\" \\\n    -o /app/server ./cmd/api\n\n# Runtime stage\nFROM scratch\n\nCOPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/\nCOPY --from=builder /app/server /server\nCOPY --from=builder /app/migrations /migrations\n\nUSER 65534:65534\n\nEXPOSE 8080\n\nENTRYPOINT [\"/server\"]\n```\n\n### Makefile\n\n```makefile\n.PHONY: build test lint run migrate\n\nBINARY := server\nVERSION := $(shell git describe --tags --always --dirty)\n\nbuild:\n\tCGO_ENABLED=0 go build -ldflags=\"-w -s -X main.version=$(VERSION)\" -o bin/$(BINARY) ./cmd/api\n\ntest:\n\tgo test -race -coverprofile=coverage.out ./...\n\tgo tool cover -func=coverage.out\n\ntest-short:\n\tgo test -race -short ./...\n\nlint:\n\tgolangci-lint run\n\nrun:\n\tgo run ./cmd/api\n\nmigrate-up:\n\tgoose -dir migrations postgres \"$(DATABASE_URL)\" up\n\nmigrate-down:\n\tgoose -dir migrations postgres \"$(DATABASE_URL)\" down\n\nmigrate-create:\n\tgoose -dir migrations create $(NAME) sql\n\ngenerate:\n\tsqlc generate\n\tmockery\n\ndocker-build:\n\tdocker build -t $(BINARY):$(VERSION) .\n\nci: lint test build\n```\n\n### golangci-lint Configuration\n\n```yaml\n# .golangci.yml\nrun:\n  timeout: 5m\n\nlinters:\n  enable:\n    - errcheck\n    - govet\n    - staticcheck\n    - unused\n    - gosimple\n    - ineffassign\n    - typecheck\n    - gocritic\n    - gofumpt\n    - revive\n    - misspell\n    - prealloc\n    - noctx         # Finds HTTP requests without context\n    - bodyclose     # Checks HTTP response body is closed\n    - sqlclosecheck # Checks sql.Rows is closed\n    - contextcheck  # Checks function whether use a non-inherited context\n    - errname       # Checks sentinel error names follow Go convention\n    - exhaustive    # Checks exhaustiveness of enum switch statements\n    - gosec         # Security-oriented linting\n    - nilerr        # Finds code returning nil even on error\n    - unparam       # Reports unused function parameters\n\nlinters-settings:\n  gocritic:\n    enabled-tags:\n      - diagnostic\n      - style\n      - performance\n  revive:\n    rules:\n      - name: unexported-return\n        disabled: true\n  gosec:\n    excludes:\n      - G104 # Unhandled errors — covered by errcheck\n\nissues:\n  exclude-rules:\n    - path: _test\\.go\n      linters:\n        - gosec\n        - errcheck\n```\n\n### GitHub Actions CI\n\n```yaml\nname: CI\non:\n  push:\n    branches: [main]\n  pull_request:\n\njobs:\n  ci:\n    runs-on: ubuntu-latest\n    \n    services:\n      postgres:\n        image: postgres:16-alpine\n        env:\n          POSTGRES_PASSWORD: test\n          POSTGRES_DB: testdb\n        ports:\n          - 5432:5432\n        options: >-\n          --health-cmd pg_isready\n          --health-interval 10s\n          --health-timeout 5s\n          --health-retries 5\n    \n    steps:\n      - uses: actions/checkout@v4\n      \n      - uses: actions/setup-go@v5\n        with:\n          go-version: '1.23'\n      \n      - name: Lint\n        uses: golangci/golangci-lint-action@v6\n        with:\n          version: latest\n      \n      - name: Test\n        run: go test -race -coverprofile=coverage.out ./...\n        env:\n          DATABASE_URL: postgres://postgres:test@localhost:5432/testdb?sslmode=disable\n      \n      - name: Coverage\n        run: |\n          COVERAGE=$(go tool cover -func=coverage.out | grep total | awk '{print $3}')\n          echo \"Coverage: $COVERAGE\"\n      \n      - name: Build\n        run: go build -o /dev/null ./...\n```\n\n---\n\n## Phase 12: Performance Optimization\n\n### Priority Stack\n\n| Priority | Technique | Impact |\n|----------|-----------|--------|\n| 1 | Connection pooling (pgx pool, HTTP client reuse) | 10-50x |\n| 2 | Avoid unnecessary allocations (sync.Pool, pre-allocated slices) | 2-5x |\n| 3 | Use `strings.Builder` for string concatenation | 5-20x |\n| 4 | Batch database operations | 5-50x |\n| 5 | Cache hot paths (sync.Map, local cache, Redis) | 10-100x |\n| 6 | Profile before optimizing (`pprof`) | — |\n\n### Profiling\n\n```go\nimport _ \"net/http/pprof\"\n\n// In main.go (debug server on separate port)\ngo func() {\n    log.Println(http.ListenAndServe(\":6060\", nil))\n}()\n\n// Then: go tool pprof http://localhost:6060/debug/pprof/heap\n// Or:   go tool pprof http://localhost:6060/debug/pprof/profile?seconds=30\n```\n\n### Common Optimizations\n\n```go\n// ✅ Pre-allocate slices when length is known\nusers := make([]User, 0, len(ids))\n\n// ✅ strings.Builder for concatenation\nvar b strings.Builder\nb.Grow(estimatedLen)\nfor _, s := range parts {\n    b.WriteString(s)\n}\nresult := b.String()\n\n// ✅ Reuse HTTP clients (never create per-request)\nvar httpClient = &http.Client{\n    Timeout: 10 * time.Second,\n    Transport: &http.Transport{\n        MaxIdleConns:        100,\n        MaxIdleConnsPerHost: 10,\n        IdleConnTimeout:     90 * time.Second,\n    },\n}\n\n// ✅ sync.Pool for frequently allocated objects\nvar bufPool = sync.Pool{\n    New: func() any {\n        return new(bytes.Buffer)\n    },\n}\n\nfunc process() {\n    buf := bufPool.Get().(*bytes.Buffer)\n    defer func() {\n        buf.Reset()\n        bufPool.Put(buf)\n    }()\n    // use buf...\n}\n```\n\n---\n\n## Phase 13: Security Hardening\n\n### Security Checklist\n\n| Category | Check | Priority |\n|----------|-------|----------|\n| Input | Validate all input with `validator/v10` | P0 |\n| SQL | Use parameterized queries (sqlc/pgx) — NEVER string concat | P0 |\n| Auth | JWT validation with proper key rotation | P0 |\n| Secrets | Environment variables only, never hardcoded | P0 |\n| Dependencies | `govulncheck` in CI, `go mod tidy` regularly | P1 |\n| CORS | Strict origin allowlist, not `*` | P1 |\n| Rate limiting | Per-IP and per-user limits | P1 |\n| Headers | Security headers middleware | P1 |\n| TLS | TLS 1.2+ only, strong ciphers | P1 |\n| Logging | Never log secrets, PII, or tokens | P2 |\n\n### Security Headers Middleware\n\n```go\nfunc SecurityHeaders(next http.Handler) http.Handler {\n    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n        w.Header().Set(\"X-Content-Type-Options\", \"nosniff\")\n        w.Header().Set(\"X-Frame-Options\", \"DENY\")\n        w.Header().Set(\"X-XSS-Protection\", \"0\")\n        w.Header().Set(\"Strict-Transport-Security\", \"max-age=63072000; includeSubDomains\")\n        w.Header().Set(\"Content-Security-Policy\", \"default-src 'none'\")\n        w.Header().Set(\"Referrer-Policy\", \"strict-origin-when-cross-origin\")\n        next.ServeHTTP(w, r)\n    })\n}\n```\n\n### Vulnerability Scanning\n\n```bash\n# Install\ngo install golang.org/x/vuln/cmd/govulncheck@latest\n\n# Scan\ngovulncheck ./...\n\n# In CI — fail build on vulnerabilities\ngovulncheck -show verbose ./...\n```\n\n---\n\n## Phase 14: Advanced Patterns\n\n### Generics (Go 1.18+)\n\n```go\n// Generic result type\ntype Result[T any] struct {\n    Data  T\n    Error error\n}\n\n// Generic repository\ntype Repository[T any] interface {\n    GetByID(ctx context.Context, id string) (*T, error)\n    List(ctx context.Context, filter Filter) ([]T, error)\n    Create(ctx context.Context, entity *T) error\n    Update(ctx context.Context, entity *T) error\n    Delete(ctx context.Context, id string) error\n}\n\n// Generic pagination\ntype Page[T any] struct {\n    Items      []T    `json:\"items\"`\n    NextCursor string `json:\"next_cursor,omitempty\"`\n    HasMore    bool   `json:\"has_more\"`\n}\n```\n\n### Functional Options Pattern\n\n```go\ntype ServerOption func(*Server)\n\nfunc WithAddr(addr string) ServerOption {\n    return func(s *Server) { s.addr = addr }\n}\n\nfunc WithTimeout(d time.Duration) ServerOption {\n    return func(s *Server) { s.timeout = d }\n}\n\nfunc WithLogger(l *slog.Logger) ServerOption {\n    return func(s *Server) { s.logger = l }\n}\n\nfunc NewServer(opts ...ServerOption) *Server {\n    s := &Server{\n        addr:    \":8080\",\n        timeout: 30 * time.Second,\n        logger:  slog.Default(),\n    }\n    for _, opt := range opts {\n        opt(s)\n    }\n    return s\n}\n```\n\n### Graceful Degradation\n\n```go\n// Circuit breaker pattern (simplified)\ntype CircuitBreaker struct {\n    failures   atomic.Int64\n    threshold  int64\n    resetAfter time.Duration\n    lastFail   atomic.Int64\n}\n\nfunc (cb *CircuitBreaker) Execute(fn func() error) error {\n    if cb.isOpen() {\n        return ErrCircuitOpen\n    }\n    \n    err := fn()\n    if err != nil {\n        cb.failures.Add(1)\n        cb.lastFail.Store(time.Now().UnixNano())\n        return err\n    }\n    \n    cb.failures.Store(0)\n    return nil\n}\n\nfunc (cb *CircuitBreaker) isOpen() bool {\n    if cb.failures.Load() < cb.threshold {\n        return false\n    }\n    // Allow retry after reset period\n    elapsed := time.Since(time.Unix(0, cb.lastFail.Load()))\n    return elapsed < cb.resetAfter\n}\n```\n\n---\n\n## 10 Go Production Commandments\n\n1. **`internal/` is the gatekeeper** — hide implementation details aggressively\n2. **Errors are values** — wrap them, check them, never ignore them\n3. **`-race` flag always** — data races are silent killers\n4. **Interfaces at the consumer** — small, focused, implicit\n5. **Context everywhere** — first param for anything doing I/O\n6. **`errgroup` for goroutines** — bounded concurrency, clean error handling\n7. **`sqlc` over ORMs** — type safety from actual SQL, zero runtime reflection\n8. **Profile before optimizing** — `pprof` doesn't lie, intuition does\n9. **Fail at startup** — validate config, check connections, panic early\n10. **Graceful shutdown** — catch signals, drain connections, close cleanly\n\n---\n\n## 10 Common Go Mistakes\n\n| Mistake | Impact | Fix |\n|---------|--------|-----|\n| Goroutine leak | Memory exhaustion | Always have termination path |\n| Missing error check | Silent failures | `errcheck` linter |\n| String concatenation in loop | O(n²) allocations | `strings.Builder` |\n| Copy mutex | Silent data race | Pass by pointer, embedder beware |\n| Ignoring context cancellation | Wasted resources | Check `ctx.Err()` |\n| `init()` abuse | Hard to test, hidden side effects | Explicit initialization |\n| Interface pollution | Over-abstraction | Only abstract at consumption point |\n| Missing defer for cleanup | Resource leaks | `defer` immediately after acquire |\n| Nil pointer on interface | Panic at runtime | Check concrete value, not interface |\n| `go func()` in loop (pre-1.22) | Wrong variable captured | `item := item` or func param |\n\n---\n\n## Production Readiness Checklist\n\n### Mandatory (P0)\n- [ ] `-race` clean test suite\n- [ ] >80% test coverage on business logic\n- [ ] Structured logging (slog/zerolog)\n- [ ] Graceful shutdown with signal handling\n- [ ] Health check endpoints (`/healthz`, `/readyz`)\n- [ ] Configuration validation at startup\n- [ ] Error wrapping with context throughout\n- [ ] golangci-lint clean (strict config)\n- [ ] Multi-stage Docker build (scratch/distroless)\n- [ ] `govulncheck` clean\n\n### Recommended (P1)\n- [ ] OpenTelemetry tracing\n- [ ] Prometheus metrics\n- [ ] Request ID propagation\n- [ ] Rate limiting\n- [ ] Security headers\n- [ ] Integration tests with testcontainers\n- [ ] Database migrations (goose/migrate)\n- [ ] CI/CD pipeline (lint → test → build → deploy)\n\n---\n\n## Quality Scoring (0-100)\n\n| Dimension | Weight | What to Evaluate |\n|-----------|--------|-----------------|\n| Error handling | 15% | Wrapping, sentinels, no swallowed errors |\n| Concurrency | 15% | Race-free, context propagation, goroutine lifecycle |\n| Testing | 15% | Coverage, table-driven, integration, -race |\n| Code organization | 15% | Package boundaries, internal/, dependency direction |\n| Observability | 10% | Structured logging, metrics, tracing |\n| Security | 10% | Input validation, govulncheck, secrets management |\n| Performance | 10% | Profiling, pooling, pre-allocation |\n| Documentation | 10% | GoDoc, README, ADRs |\n\n**Grade:** 0-40 = 🔴 Needs rewrite | 41-60 = 🟡 Significant gaps | 61-80 = 🟢 Production ready | 81-100 = 💎 Exemplary\n\n---\n\n## Natural Language Commands\n\nWhen asked about Go projects, interpret these naturally:\n- \"Review this Go code\" → Run quick health check, identify anti-patterns\n- \"Set up a new Go service\" → Generate full project structure with all phases\n- \"Fix the error handling\" → Apply Phase 2 patterns throughout\n- \"Add tests\" → Generate table-driven tests following Phase 5\n- \"Make this production ready\" → Run through production readiness checklist\n- \"Profile this\" → Guide through pprof analysis\n- \"Add observability\" → Apply Phase 10 (OTel + Prometheus)\n- \"Optimize performance\" → Profile first, then apply Phase 12 priority stack\n- \"Set up CI\" → Generate GitHub Actions + golangci-lint config\n- \"Add database\" → pgx pool + sqlc + migration setup\n- \"Review architecture\" → Evaluate against Phase 1 rules\n- \"Security audit\" → Run through Phase 13 checklist\n","readmeExcerpt":"Go Production Engineering You are a Go production engineering expert. Follow this system for every Go project — from architecture decisions through production deployment. Apply phases sequentially for new projects; use individual phases as needed for existing codebases. --- Quick Health Check (/16) Score 0 (missing), 1 (partial), or 2 (solid) for each signal: | Signal | What to Check | |--------|--------------| | Pro","codeSnippets":[],"executableExamples":[{"language":"text","snippet":"project-root/\n├── cmd/\n│   ├── api/              # HTTP API binary\n│   │   └── main.go\n│   └── worker/           # Background worker binary\n│       └── main.go\n├── internal/             # Private packages (enforced by Go)\n│   ├── domain/           # Business types & interfaces\n│   │   ├── user.go\n│   │   └── order.go\n│   ├── service/          # Business logic\n│   │   ├── user.go\n│   │   └── user_test.go\n│   ├── repository/       # Data access\n│   │   ├── postgres/\n│   │   └── redis/\n│   ├── handler/          # HTTP/gRPC handlers\n│   │   ├── http/\n│   │   └── grpc/\n│   ├── middleware/        # HTTP middleware\n│   └── config/           # Configuration\n├── pkg/                  # Public packages (use sparingly)\n├── api/                  # OpenAPI specs, proto files\n├── migrations/           # Database migrations\n├── scripts/              # Build/deploy scripts\n├── Makefile\n├── Dockerfile\n├── go.mod\n├── go.sum\n└── .golangci.yml"},{"language":"go","snippet":"// cmd/api/main.go — wire everything here\nfunc main() {\n    cfg := config.MustLoad()\n    \n    // Infrastructure\n    db := postgres.MustConnect(cfg.Database)\n    cache := redis.MustConnect(cfg.Redis)\n    logger := logging.New(cfg.Log)\n    \n    // Repositories\n    userRepo := postgres.NewUserRepository(db)\n    orderRepo := postgres.NewOrderRepository(db)\n    \n    // Services\n    userSvc := service.NewUserService(userRepo, cache, logger)\n    orderSvc := service.NewOrderService(orderRepo, userSvc, logger)\n    \n    // Handlers\n    router := handler.NewRouter(userSvc, orderSvc, logger)\n    \n    // Server\n    srv := &http.Server{\n        Addr:         cfg.Server.Addr,\n        Handler:      router,\n        ReadTimeout:  cfg.Server.ReadTimeout,\n        WriteTimeout: cfg.Server.WriteTimeout,\n        IdleTimeout:  cfg.Server.IdleTimeout,\n    }\n    \n    // Graceful shutdown\n    go func() {\n        if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {\n            logger.Fatal(\"server failed\", \"error\", err)\n        }\n    }()\n    \n    quit := make(chan os.Signal, 1)\n    signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)\n    <-quit\n    \n    ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)\n    defer cancel()\n    \n    if err := srv.Shutdown(ctx); err != nil {\n        logger.Fatal(\"forced shutdown\", \"error\", err)\n    }\n}"},{"language":"go","snippet":"// internal/domain/errors.go — sentinel errors\npackage domain\n\nimport \"errors\"\n\nvar (\n    ErrNotFound      = errors.New(\"not found\")\n    ErrConflict      = errors.New(\"conflict\")\n    ErrUnauthorized  = errors.New(\"unauthorized\")\n    ErrForbidden     = errors.New(\"forbidden\")\n    ErrValidation    = errors.New(\"validation error\")\n    ErrInternal      = errors.New(\"internal error\")\n)\n\n// Typed error with context\ntype ValidationError struct {\n    Field   string\n    Message string\n}\n\nfunc (e *ValidationError) Error() string {\n    return fmt.Sprintf(\"validation: %s — %s\", e.Field, e.Message)\n}\n\nfunc (e *ValidationError) Unwrap() error {\n    return ErrValidation\n}"},{"language":"go","snippet":"// ✅ GOOD: Wrap with context using fmt.Errorf %w\nfunc (r *UserRepo) GetByID(ctx context.Context, id string) (*User, error) {\n    user, err := r.db.QueryRow(ctx, query, id)\n    if err != nil {\n        if errors.Is(err, pgx.ErrNoRows) {\n            return nil, fmt.Errorf(\"user %s: %w\", id, domain.ErrNotFound)\n        }\n        return nil, fmt.Errorf(\"get user %s: %w\", id, err)\n    }\n    return user, nil\n}\n\n// ❌ BAD: Swallowed error\nif err != nil {\n    log.Println(err) // logged but not returned — caller doesn't know it failed\n    return nil\n}\n\n// ❌ BAD: Bare return\nif err != nil {\n    return err // no context — impossible to debug in production\n}\n\n// ❌ BAD: String wrapping (breaks errors.Is/As)\nreturn fmt.Errorf(\"failed: %s\", err) // use %w, not %s or %v"},{"language":"go","snippet":"func mapError(err error) (int, string) {\n    switch {\n    case errors.Is(err, domain.ErrNotFound):\n        return http.StatusNotFound, \"resource not found\"\n    case errors.Is(err, domain.ErrConflict):\n        return http.StatusConflict, \"resource already exists\"\n    case errors.Is(err, domain.ErrUnauthorized):\n        return http.StatusUnauthorized, \"authentication required\"\n    case errors.Is(err, domain.ErrForbidden):\n        return http.StatusForbidden, \"insufficient permissions\"\n    case errors.Is(err, domain.ErrValidation):\n        var ve *domain.ValidationError\n        if errors.As(err, &ve) {\n            return http.StatusBadRequest, ve.Error()\n        }\n        return http.StatusBadRequest, \"invalid request\"\n    default:\n        return http.StatusInternalServerError, \"internal server error\"\n    }\n}"},{"language":"go","snippet":"// Every function that does I/O takes context as first parameter\nfunc (s *OrderService) Create(ctx context.Context, req CreateOrderRequest) (*Order, error) {\n    // Check cancellation before expensive operations\n    select {\n    case <-ctx.Done():\n        return nil, ctx.Err()\n    default:\n    }\n    \n    user, err := s.userRepo.GetByID(ctx, req.UserID)\n    if err != nil {\n        return nil, fmt.Errorf(\"get user: %w\", err)\n    }\n    \n    order, err := s.orderRepo.Create(ctx, user, req)\n    if err != nil {\n        return nil, fmt.Errorf(\"create order: %w\", err)\n    }\n    \n    // Fire-and-forget with NEW context (don't use request context)\n    go func() {\n        bgCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)\n        defer cancel()\n        _ = s.notifier.SendOrderConfirmation(bgCtx, order)\n    }()\n    \n    return order, nil\n}"}],"parameters":{},"dependencies":[],"permissions":[],"extractedFiles":[],"languages":["typescript"],"docsSourceLabel":"CLAWHUB","editorialOverview":"Go Production Engineering Go Production Engineering You are a Go production engineering expert. Follow this system for every Go project — from architecture decisions through production deployment. Apply phases sequentially for new projects; use individual phases as needed for existing codebases. --- Quick Health Check (/16) Score 0 (missing), 1 (partial), or 2 (solid) for each signal: | Signal | What to Check | |--------|--------------| | Pro","editorialQuality":{"score":100,"threshold":65,"status":"ready","wordCount":366,"uniquenessScore":66,"reasons":[]}},"media":{"evidence":{"source":"no-media","verified":false,"confidence":"low","updatedAt":"2026-04-15T00:45:39.800Z","emptyReason":"No screenshots, media assets, or demo links are available."},"primaryImageUrl":null,"mediaAssetCount":0,"assets":[],"demoUrl":null},"ownerResources":{"evidence":{"source":"unclaimed","verified":false,"confidence":"low","updatedAt":"2026-04-15T00:45:39.800Z","emptyReason":"This page has not been claimed by the agent owner."},"hasCustomPage":false,"customPageUpdatedAt":null,"customLinks":[],"structuredLinks":{"docsUrl":null,"demoUrl":null,"supportUrl":null,"pricingUrl":null,"statusUrl":null},"customPage":null},"relatedAgents":{"evidence":{"source":"protocol-neighbors","verified":false,"confidence":"medium","updatedAt":"2026-10-10T03:41:57.076Z","emptyReason":null},"items":[{"id":"8ebccd8e-3863-4187-8355-c3f14e1f9edf","entityType":"agent","canonicalPath":"/agent/iofficeai-aionui","slug":"iofficeai-aionui","name":"AionUi","description":"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!","url":"https://github.com/iOfficeAI/AionUi","homepage":"https://www.aionui.com","source":"GITHUB_REPOS","protocols":["MCP","OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-10-09T19:11:12.944Z","createdAt":"2026-02-25T03:38:16.584Z","downloads":null},{"id":"b917f68a-ebff-438e-84f8-3f4b2494c0bc","entityType":"agent","canonicalPath":"/agent/activepieces-activepieces","slug":"activepieces-activepieces","name":"activepieces","description":"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","url":"https://github.com/activepieces/activepieces","homepage":"https://www.activepieces.com","source":"GITHUB_REPOS","protocols":["OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-04-15T02:22:12.426Z","createdAt":"2026-02-25T03:38:12.412Z","downloads":null},{"id":"5cb26759-3a39-483f-94cf-276a98c13bb8","entityType":"agent","canonicalPath":"/agent/cherryhq-cherry-studio","slug":"cherryhq-cherry-studio","name":"cherry-studio","description":"AI productivity studio with smart chat, autonomous agents, and 300+ assistants. Unified access to frontier LLMs","url":"https://github.com/CherryHQ/cherry-studio","homepage":"https://cherry-ai.com","source":"GITHUB_REPOS","protocols":["MCP","OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-04-11T14:38:40.986Z","createdAt":"2026-02-25T03:38:19.379Z","downloads":null},{"id":"6f6582d0-5d76-4f0f-b81d-86520247950b","entityType":"agent","canonicalPath":"/agent/copilotkit-copilotkit","slug":"copilotkit-copilotkit","name":"CopilotKit","description":"The Frontend for Agents & Generative UI. React + Angular","url":"https://github.com/CopilotKit/CopilotKit","homepage":"https://docs.copilotkit.ai","source":"GITHUB_REPOS","protocols":["OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-03-25T09:50:57.846Z","createdAt":"2026-02-25T03:39:14.617Z","downloads":null}],"links":{"hub":"/agent","source":"/agent/source/clawhub","protocols":[{"label":"OpenClaw","href":"/agent/protocol/openclew"}]}}}