GO

go-patterns

A Go pattern guide for building robust, high-concurrency systems and clean code architectures.

Install

mkdir -p .claude/skills/go-patterns && curl -L -o skill.zip "https://agentskills.codes/api/skills/download/9782" && unzip -o skill.zip -d .claude/skills/go-patterns && rm skill.zip

Installs to .claude/skills/go-patterns

Activation

This is the description your AI agent reads to decide when to run this skill — the better it matches your request, the more reliably it fires.

Các mẫu thiết kế Go: concurrency, interfaces, error handling và clean architecture.
83 charsno explicit “when” trigger
Intermediate

Key capabilities

  • Implement interface-driven design
  • Handle errors with sentinel types
  • Build worker pool concurrency
  • Apply functional options pattern
  • Chain HTTP middleware

How it works

It provides standard Go patterns for concurrency, error handling, and clean architecture using idiomatic language features.

Inputs & outputs

You give it
Problem statement or architectural requirement
You get back
Idiomatic Go implementation pattern

When to use go-patterns

  • Building microservices
  • Writing concurrent Go code
  • Implementing clean architecture

About this skill

Go Patterns

Status: Active | Version: 1.0.0

When to Use

  • Building microservices and distributed systems
  • High-concurrency servers (APIs, gRPC, WebSocket)
  • DevOps tooling and CLI applications
  • Cloud-native infrastructure (Kubernetes operators, controllers)

Core Patterns

1. Interface-Driven Design

// Small interfaces — Go proverb: "The bigger the interface, the weaker the abstraction"
type Reader interface {
    Read(p []byte) (n int, err error)
}

type UserRepository interface {
    FindByID(ctx context.Context, id string) (*User, error)
    Create(ctx context.Context, user *User) error
}

// Accept interfaces, return structs
func NewUserService(repo UserRepository, logger *slog.Logger) *UserService {
    return &UserService{repo: repo, logger: logger}
}

2. Error Handling

import "fmt"

// Sentinel errors for comparison
var (
    ErrNotFound     = fmt.Errorf("not found")
    ErrUnauthorized = fmt.Errorf("unauthorized")
)

// Wrap errors with context
func (s *UserService) GetUser(ctx context.Context, id string) (*User, error) {
    user, err := s.repo.FindByID(ctx, id)
    if err != nil {
        return nil, fmt.Errorf("get user %s: %w", id, err)
    }
    return user, nil
}

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

3. Concurrency Patterns

// Worker pool
func processItems(ctx context.Context, items []Item, workers int) []Result {
    in := make(chan Item, len(items))
    out := make(chan Result, len(items))

    var wg sync.WaitGroup
    for i := 0; i < workers; i++ {
        wg.Add(1)
        go func() {
            defer wg.Done()
            for item := range in {
                out <- process(item)
            }
        }()
    }

    for _, item := range items {
        in <- item
    }
    close(in)

    go func() {
        wg.Wait()
        close(out)
    }()

    var results []Result
    for r := range out {
        results = append(results, r)
    }
    return results
}

// Context with cancellation
func longRunningTask(ctx context.Context) error {
    select {
    case <-ctx.Done():
        return ctx.Err()
    case result := <-doWork():
        return handleResult(result)
    }
}

4. Functional Options

type Server struct {
    host    string
    port    int
    timeout time.Duration
}

type Option func(*Server)

func WithHost(host string) Option {
    return func(s *Server) { s.host = host }
}
func WithPort(port int) Option {
    return func(s *Server) { s.port = port }
}
func WithTimeout(t time.Duration) Option {
    return func(s *Server) { s.timeout = t }
}

func NewServer(opts ...Option) *Server {
    s := &Server{host: "0.0.0.0", port: 8080, timeout: 30 * time.Second}
    for _, opt := range opts {
        opt(s)
    }
    return s
}

5. Middleware Pattern

type Middleware func(http.Handler) http.Handler

func Logging(logger *slog.Logger) Middleware {
    return func(next http.Handler) http.Handler {
        return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
            start := time.Now()
            next.ServeHTTP(w, r)
            logger.Info("request", "method", r.Method, "path", r.URL.Path, "duration", time.Since(start))
        })
    }
}

func Chain(h http.Handler, middlewares ...Middleware) http.Handler {
    for i := len(middlewares) - 1; i >= 0; i-- {
        h = middlewares[i](h)
    }
    return h
}

Project Structure

cmd/
├── api/main.go           # API server entry
├── worker/main.go         # Background worker
internal/
├── config/config.go       # Configuration
├── domain/                # Domain models
├── handler/               # HTTP handlers
├── service/               # Business logic
├── repository/            # Data access
├── middleware/             # HTTP middleware
pkg/
├── logger/                # Shared logger
├── validator/             # Input validation

Key Dependencies (2026)

PackagePurposeNote
net/httpHTTP serverstdlib
log/slogStructured loggingstdlib (Go 1.21+)
database/sqlDatabasestdlib
github.com/gin-gonic/ginWeb frameworkPopular
github.com/go-chi/chiLightweight routerIdiomatic
google.golang.org/grpcgRPCGoogle
github.com/jackc/pgxPostgreSQL driverFast
github.com/stretchr/testifyTestingAssert + Mock

Quality Checklist

go fmt ./...           # Format
go vet ./...           # Static analysis
golangci-lint run      # Comprehensive lint
go test ./... -race    # Tests with race detector
go build ./...         # Build check

When not to use it

  • Non-Go projects

Prerequisites

Go runtime

Limitations

  • Limited to Go language patterns
  • Requires knowledge of Go standard library

How it compares

It focuses on Go-specific idioms like small interfaces and functional options rather than generic OOP patterns.

Compared to similar skills

go-patterns side by side with the closest alternatives in the catalog.

SkillInstallsUpdatedSafetyDifficulty
go-patterns (this skill)05moReviewIntermediate
golang-pro144moNo flagsAdvanced
go-concurrency-patterns72moNo flagsAdvanced
generating-grpc-services124dReviewAdvanced

Try saying

Example prompts that trigger this skill in your AI assistant.

You might also like

golang-pro

sickn33

Master Go 1.21+ with modern patterns, advanced concurrency, performance optimization, and production-ready microservices. Expert in the latest Go ecosystem including generics, workspaces, and cutting-edge frameworks. Use PROACTIVELY for Go development, architecture design, or performance optimization.

1479

go-concurrency-patterns

wshobson

Master Go concurrency with goroutines, channels, sync primitives, and context. Use when building concurrent Go applications, implementing worker pools, or debugging race conditions.

782

generating-grpc-services

jeremylongshore

Generate gRPC service definitions, stubs, and implementations from Protocol Buffers. Use when creating high-performance gRPC services. Trigger with phrases like "generate gRPC service", "create gRPC API", or "build gRPC server".

13

go-context

ComeOnOliver

Use when working with context.Context in Go — placement in signatures, propagating cancellation and deadlines, and storing values in context vs parameters. Also use when cancelling long-running operations, setting timeouts, or passing request-scoped data, even if they don't mention context.Context d

00

architecture-patterns

wshobson

Implement proven backend architecture patterns including Clean Architecture, Hexagonal Architecture, and Domain-Driven Design. Use when architecting complex backend systems or refactoring existing applications for better maintainability.

55214

workflow-orchestration-patterns

wshobson

Design durable workflows with Temporal for distributed systems. Covers workflow vs activity separation, saga patterns, state management, and determinism constraints. Use when building long-running processes, distributed transactions, or microservice orchestration.

10117

Search skills

Search the agent skills registry