Now liveThe Skillselion MCP - thousands of ranked skills, loaded into your agent mid-task. No install.Get it →
affaan-m avatar

Golang Patterns

  • 1.5k installs
  • 238k repo stars
  • Updated August 5, 2026
  • affaan-m/ecc

This is a copy of golang-patterns by affaan-m - installs and ranking accrue to the original listing.

golang-patterns is an ECC Go skill that applies idiomatic design patterns including functional options, small interfaces, and concurrency primitives for developers writing maintainable Go services.

About

golang-patterns is an affaan-m/ecc skill activated on **/*.go, **/go.mod, and **/go.sum files, extending design principles with Go-specific idioms. Coverage includes functional options constructors, small interface design, dependency injection, concurrency patterns, error handling discipline, and package organization. Example snippets show Option func(*Server) helpers like WithPort for flexible configuration without sprawling constructors. Developers reach for golang-patterns when refactoring Go microservices, CLIs, or libraries to avoid fighting language quirks and to align new modules with community-accepted structure before code review.

  • Enforces simplicity and clarity over clever code
  • Teaches making the zero value useful for types and structs
  • Guides error handling, package design, and module conventions
  • Activates for writing, reviewing, refactoring, or designing Go code
  • Provides concrete good-vs-bad code examples for every principle

Golang Patterns by the numbers

  • 1,477 all-time installs (skills.sh)
  • +86 installs in the week ending Aug 5, 2026 (Skillselion tracking)
  • Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/affaan-m/ecc --skill golang-patterns

Add your badge

Show developers this skill is listed on Skillselion. Paste this into your README.

Listed on Skillselion
Installs1.5k
repo stars238k
Last updatedAugust 5, 2026
Repositoryaffaan-m/ecc

What are idiomatic Go patterns for services and packages?

Produce clean, idiomatic, and maintainable Go code without fighting language quirks.

Who is it for?

Go developers refactoring or authoring services who want ECC-curated idioms instead of ad hoc struct wiring.

Skip if: Non-Go codebases or teams needing framework-specific guides like Gin or Echo routing tutorials only.

When should I use this skill?

An agent edits .go files or go.mod and needs idiomatic Go structure, options pattern, or concurrency guidance.

What you get

Refactored Go modules with functional options, interface boundaries, and organized package layouts.

  • Idiomatic Go refactors
  • Functional options constructors

Files

SKILL.mdMarkdownGitHub ↗

Go Patterns

This skill provides comprehensive Go patterns extending common design principles with Go-specific idioms.

Functional Options

Use the functional options pattern for flexible constructor configuration:

type Option func(*Server)

func WithPort(port int) Option {
    return func(s *Server) { s.port = port }
}

func NewServer(opts ...Option) *Server {
    s := &Server{port: 8080}
    for _, opt := range opts {
        opt(s)
    }
    return s
}

Benefits:

  • Backward compatible API evolution
  • Optional parameters with defaults
  • Self-documenting configuration

Small Interfaces

Define interfaces where they are used, not where they are implemented.

Principle: Accept interfaces, return structs

// Good: Small, focused interface defined at point of use
type UserStore interface {
    GetUser(id string) (*User, error)
}

func ProcessUser(store UserStore, id string) error {
    user, err := store.GetUser(id)
    // ...
}

Benefits:

  • Easier testing and mocking
  • Loose coupling
  • Clear dependencies

Dependency Injection

Use constructor functions to inject dependencies:

func NewUserService(repo UserRepository, logger Logger) *UserService {
    return &UserService{
        repo:   repo,
        logger: logger,
    }
}

Pattern:

  • Constructor functions (New* prefix)
  • Explicit dependencies as parameters
  • Return concrete types
  • Validate dependencies in constructor

Concurrency Patterns

Worker Pool

func workerPool(jobs <-chan Job, results chan<- Result, workers int) {
    var wg sync.WaitGroup
    for i := 0; i < workers; i++ {
        wg.Add(1)
        go func() {
            defer wg.Done()
            for job := range jobs {
                results <- processJob(job)
            }
        }()
    }
    wg.Wait()
    close(results)
}

Context Propagation

Always pass context as first parameter:

func FetchUser(ctx context.Context, id string) (*User, error) {
    // Check context cancellation
    select {
    case <-ctx.Done():
        return nil, ctx.Err()
    default:
    }
    // ... fetch logic
}

Error Handling

Error Wrapping

if err != nil {
    return fmt.Errorf("failed to fetch user %s: %w", id, err)
}

Custom Errors

type ValidationError struct {
    Field string
    Msg   string
}

func (e *ValidationError) Error() string {
    return fmt.Sprintf("%s: %s", e.Field, e.Msg)
}

Sentinel Errors

var (
    ErrNotFound = errors.New("not found")
    ErrInvalid  = errors.New("invalid input")
)

// Check with errors.Is
if errors.Is(err, ErrNotFound) {
    // handle not found
}

Package Organization

Structure

project/
├── cmd/              # Main applications
│   └── server/
│       └── main.go
├── internal/         # Private application code
│   ├── domain/       # Business logic
│   ├── handler/      # HTTP handlers
│   └── repository/   # Data access
└── pkg/              # Public libraries

Naming Conventions

  • Package names: lowercase, single word
  • Avoid stutter: user.User not user.UserModel
  • Use internal/ for private code
  • Keep main package minimal

Testing Patterns

Table-Driven Tests

func TestValidate(t *testing.T) {
    tests := []struct {
        name    string
        input   string
        wantErr bool
    }{
        {"valid", "test@example.com", false},
        {"invalid", "not-an-email", true},
    }

    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            err := Validate(tt.input)
            if (err != nil) != tt.wantErr {
                t.Errorf("got error %v, wantErr %v", err, tt.wantErr)
            }
        })
    }
}

Test Helpers

func testDB(t *testing.T) *sql.DB {
    t.Helper()
    db, err := sql.Open("sqlite3", ":memory:")
    if err != nil {
        t.Fatalf("failed to open test db: %v", err)
    }
    t.Cleanup(func() { db.Close() })
    return db
}

When to Use This Skill

  • Designing Go APIs and packages
  • Implementing concurrent systems
  • Structuring Go projects
  • Writing idiomatic Go code
  • Refactoring Go codebases

Related skills

How it compares

Use golang-patterns over generic design-pattern skills when the codebase is Go and needs module-level idioms tied to go.mod structure.

FAQ

Which files trigger golang-patterns?

golang-patterns metadata globs target **/*.go, **/go.mod, and **/go.sum so agents apply ECC Go idioms when editing Go source or module files.

What patterns does golang-patterns cover?

golang-patterns covers functional options, small interfaces, dependency injection, concurrency, error handling, and package organization for maintainable Go code.

Backend & APIsbackendintegrations

This week in AI coding

Five minutes, every Monday - the tools, releases and tactics for developers.

unsubscribe anytime.