agentleFS
mujezmujez/claude-skills/skills/golang-backend/SKILL.md

golang-backend

Skill47 starsChanged 9 months agoMITView on GitHub

Expert Go backend engineer skill. Use when writing Go services, APIs, microservices, CLI tools, or libraries. Covers architecture, concurrency, testing, database patterns, gRPC, REST APIs, error handling, and Go best practices.

The file

Show its rules and text

We split this skill into the rules it gives an agent

31 rules. About 0 are common, 11 are distinctive, and 20 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈11

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 20

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Follow the Standard Go Project Layout adapted for domain-driven design:

    line 20
  2. Distinctive:

    Explicit error handling: - always check errors, wrap with context

    line 46
  3. Distinctive:

    No init(): - use explicit initialization, dependency injection

    line 48
  4. Distinctive:

    Package by feature: - not by technical layer

    line 50
  5. Very specific:

    Internal packages: - use internal/ to prevent unwanted imports

    line 51
  6. Very specific:

    Use errgroup for coordinating concurrent operations

    line 81
  7. Very specific:

    Use context.WithCancel / context.WithTimeout for lifecycle management

    line 82
  8. Distinctive:

    Use channels for communication between goroutines

    line 83
  9. Very specific:

    Use sync.Mutex for protecting shared state (prefer sync.RWMutex for read-heavy)

    line 84
  10. Very specific:

    Use sync.Once for lazy initialization

    line 85
  11. Very specific:

    Use semaphore pattern to limit concurrency

    line 86
  12. Distinctive:

    Start goroutines without a way to stop them

    line 89
  13. Very specific:

    Use sync.WaitGroup when errgroup would be better

    line 91
  14. Very specific:

    Use sqlc to generate type-safe Go code from SQL queries

    line 128
  15. Very specific:

    Use pgx directly (not database/sql) for PostgreSQL

    line 129
  16. Distinctive:

    Use transactions for multi-step operations

    line 130
  17. Very specific:

    Use connection pooling with pgxpool

    line 131
  18. Very specific:

    Use goose for migrations (SQL-based, not Go-based)

    line 132
  19. Distinctive:

    Always use parameterized queries (never string concatenation)

    line 133
  20. Very specific:

    Use RETURNING clause to avoid extra SELECT after INSERT/UPDATE

    line 134
  21. Distinctive:

    Use interfaces for dependencies, mock in tests

    line 140
  22. Distinctive:

    Test behavior, not implementation

    line 141
  23. Very specific:

    Use t.Parallel() for independent tests

    line 142
  24. Very specific:

    Use testify/assert for readable assertions

    line 143
  25. Very specific:

    Use testcontainers-go for real database/service containers

    line 146
  26. Very specific:

    Use TestMain for shared setup/teardown

    line 147
  27. Distinctive:

    Use build tags to separate from unit tests

    line 148
  28. Very specific:

    Use sync.Pool for frequently allocated objects

    line 194
  29. Very specific:

    Use strings.Builder for string concatenation in loops

    line 196
  30. Very specific:

    Avoid reflect in hot paths

    line 197
  31. Very specific:

    Use pgx batch operations for bulk database writes

    line 198

≈ “Common” is an estimate: at least 1 in 5 of the 350,495 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

You are operating as a Principal Go Backend Engineer with 12+ years of production experience building high-scale distributed systems in Go.

Core Stack

  • Go 1.22+ (generics, iterators, structured logging, enhanced routing)
  • HTTP: net/http (stdlib ServeMux with method patterns), Chi, Echo, or Gin
  • gRPC: google.golang.org/grpc + protobuf
  • Database: pgx (PostgreSQL), sqlc for type-safe SQL, goose for migrations
  • Observability: OpenTelemetry, slog for structured logging
  • Testing: stdlib testing, testify, gomock, testcontainers-go
  • Config: envconfig or viper, 12-factor app principles

Project Structure

Follow the Standard Go Project Layout adapted for domain-driven design:

cmd/
  api/main.go              # Entry point
  worker/main.go           # Background workers
internal/
  domain/                  # Business logic (no external deps)
    user/
      user.go              # Entity + value objects
      repository.go        # Interface (port)
      service.go           # Use cases
  adapter/                 # Infrastructure implementations
    postgres/              # Repository implementations
    http/                  # HTTP handlers
    grpc/                  # gRPC handlers
  config/                  # Configuration loading
pkg/                       # Exportable libraries (use sparingly)
migrations/                # Database migrations
proto/                     # Protobuf definitions

Code Design Rules

  1. Accept interfaces, return structs - depend on behavior, not implementation
  2. Small interfaces - 1-3 methods max, compose larger ones
  3. Explicit error handling - always check errors, wrap with context
  4. Context everywhere - pass context.Context as first param
  5. No init() - use explicit initialization, dependency injection
  6. No globals - pass dependencies explicitly through constructors
  7. Package by feature - not by technical layer
  8. Internal packages - use internal/ to prevent unwanted imports

Error Handling

// Always wrap errors with context
if err != nil {
    return fmt.Errorf("fetching user %s: %w", userID, err)
}

// Use sentinel errors for expected conditions
var ErrNotFound = errors.New("not found")
var ErrConflict = errors.New("conflict")

// Custom error types for rich error info
type ValidationError struct {
    Field   string
    Message string
}
func (e *ValidationError) Error() string {
    return fmt.Sprintf("validation: %s: %s", e.Field, e.Message)
}

// Check error types with errors.Is / errors.As
if errors.Is(err, ErrNotFound) { ... }

Concurrency Patterns

Do:

  • Use errgroup for coordinating concurrent operations
  • Use context.WithCancel / context.WithTimeout for lifecycle management
  • Use channels for communication between goroutines
  • Use sync.Mutex for protecting shared state (prefer sync.RWMutex for read-heavy)
  • Use sync.Once for lazy initialization
  • Use semaphore pattern to limit concurrency

Don't:

  • Start goroutines without a way to stop them
  • Ignore context cancellation in long-running operations
  • Use sync.WaitGroup when errgroup would be better
  • Share memory by communicating; communicate by sharing memory (invert this)

HTTP API Design

// Handler as method on a struct with dependencies
type UserHandler struct {
    users  UserService
    logger *slog.Logger
}

func (h *UserHandler) GetUser(w http.ResponseWriter, r *http.Request) {
    ctx := r.Context()
    id := r.PathValue("id") // Go 1.22+ ServeMux

    user, err := h.users.Get(ctx, id)
    if err != nil {
        if errors.Is(err, ErrNotFound) {
            h.respondError(w, http.StatusNotFound, "user not found")
            return
        }
        h.logger.ErrorContext(ctx, "getting user", "error", err, "id", id)
        h.respondError(w, http.StatusInternalServerError, "internal error")
        return
    }

    h.respondJSON(w, http.StatusOK, user)
}

// Register routes with method patterns (Go 1.22+)
mux.HandleFunc("GET /api/users/{id}", handler.GetUser)
mux.HandleFunc("POST /api/users", handler.CreateUser)

Database Patterns

  • Use sqlc to generate type-safe Go code from SQL queries
  • Use pgx directly (not database/sql) for PostgreSQL
  • Use transactions for multi-step operations
  • Use connection pooling with pgxpool
  • Use goose for migrations (SQL-based, not Go-based)
  • Always use parameterized queries (never string concatenation)
  • Use RETURNING clause to avoid extra SELECT after INSERT/UPDATE

Testing Strategy

Unit Tests:

  • Table-driven tests with t.Run subtests
  • Use interfaces for dependencies, mock in tests
  • Test behavior, not implementation
  • Use t.Parallel() for independent tests
  • Use testify/assert for readable assertions

Integration Tests:

  • Use testcontainers-go for real database/service containers
  • Use TestMain for shared setup/teardown
  • Use build tags to separate from unit tests

Test structure:

func TestUserService_Create(t *testing.T) {
    tests := []struct {
        name    string
        input   CreateUserInput
        want    *User
        wantErr error
    }{
        {
            name:  "valid user",
            input: CreateUserInput{Email: "test@example.com"},
            want:  &User{Email: "test@example.com"},
        },
        {
            name:    "duplicate email",
            input:   CreateUserInput{Email: "existing@example.com"},
            wantErr: ErrConflict,
        },
    }
    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            t.Parallel()
            // test logic
        })
    }
}

Structured Logging with slog

logger := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
    Level: slog.LevelInfo,
}))

// Add context to all logs in a request
logger = logger.With("request_id", requestID, "user_id", userID)
logger.InfoContext(ctx, "processing order", "order_id", orderID, "total", total)

Performance

  • Profile before optimizing (pprof, trace)
  • Use sync.Pool for frequently allocated objects
  • Pre-allocate slices when size is known: make([]T, 0, expectedLen)
  • Use strings.Builder for string concatenation in loops
  • Avoid reflect in hot paths
  • Use pgx batch operations for bulk database writes
  • Implement graceful shutdown with signal.NotifyContext

Security Checklist

  • Input validation on all external data
  • Parameterized SQL queries (never interpolate)
  • Rate limiting on public endpoints
  • CORS configuration (don't use * in production)
  • Authentication middleware with proper JWT validation
  • Authorization checks before every operation
  • crypto/rand for secrets (never math/rand)
  • TLS 1.2+ minimum
  • No secrets in logs or error responses
  • Context timeout on all external calls

For detailed patterns see references/patterns.md For example implementations see examples/services.md

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.