Przejdź do treści
Biblioteka skilli
Programowanie · Nauka i wyjaśnianie

go-design-patterns

/go-design-patterns

Podaje idiomatyczne wzorce projektowe w Go: opcje funkcyjne, builder, fabryka, strategia, łańcuch middleware, pub/sub i inne dopasowane do systemu typów.

Licencja
MIT
Ostatnia zmiana repozytorium
15.10.2026

Ocena i bezpieczeństwo

100/ 100Klasa: dobry
Format25 / 25
Frontmatter z nazwą i opisem, poprawna nazwa, opis do 1024 znaków, nazwa zgodna z folderem.
Odkrywalność25 / 25
Opis mówi, kiedy użyć skilla, ma sensowną długość i jest w 3. osobie.
Treść35 / 35
Co najmniej 150 słów i do 500 linii, nagłówki, listy kroków, przykłady albo kod.
Higiena15 / 15
Bez zaślepek typu TODO, bez ścieżek Windows, z licencją.
Ryzykobrak sygnałów w skanie
Pliki w paczce
4
Skrypty
0
Komentarze HTML
0
Adresy URL w SKILL.md
0
Przestarzałość

Brak sygnałów. Repozytorium zmienione 15.10.2026, bez odwołań do wycofanych modeli i API.

Licencja

MIT, otwarta: można używać i zmieniać, z zachowaniem informacji o autorze.

Co robi i kiedy

Podaje idiomatyczne wzorce projektowe w Go: opcje funkcyjne, builder, fabryka, strategia, łańcuch middleware, pub/sub i inne dopasowane do systemu typów.

Wyzwalacze z opisu

s type system. Use when:functional optionsbuilder patternfactory patternstrategy patternmiddleware chainoption patternhow to structure this
Oryginalny opis (EN)

Idiomatic Go design patterns: functional options, builder, factory, strategy, middleware chain, pub/sub, and other patterns adapted for Go's type system. Use when: "design pattern", "functional options", "builder pattern", "factory pattern", "strategy pattern", "middleware chain", "option pattern", "how to structure this". Not for: interface design (go-interface-design), package layout (go-architecture-review), concurrency patterns (go-concurrency-review).

Jak działa

  1. Pattern Selection
  2. 1. Functional Options (essentials)
  3. 2. Constructor Rules
  4. 3. Factory
  5. 4. Middleware Chain
  6. 5. Zero Values First
  7. 6. Resilience
  8. 7. Make Illegal States Unrepresentable
  9. Anti-Patterns to Avoid
  10. Verification Checklist
Sekcje z nagłówków SKILL.md, w oryginale · 190 linii, 981 słów
Podgląd SKILL.md
---
name: go-design-patterns
description: >
  Idiomatic Go design patterns: functional options, builder, factory,
  strategy, middleware chain, pub/sub, and other patterns adapted for Go's
  type system. Use when: "design pattern", "functional options", "builder
  pattern", "factory pattern", "strategy pattern", "middleware chain",
  "option pattern", "how to structure this".
  Not for: interface design (go-interface-design), package layout
  (go-architecture-review), concurrency patterns (go-concurrency-review).
user-invocable: true
license: MIT
compatibility: Designed for Claude Code or similar AI coding agents working on Go projects. Requires the Go toolchain.
allowed-tools: Read Edit Write Glob Grep Bash(go:*) Bash(gofmt:*)
metadata:
  author: eduardo-sl
  version: "1.3.1"
---

# Go Design Patterns

Go favors composition over inheritance and simplicity over abstraction.
These patterns are idiomatic Go — not Java patterns ported to Go.

> Community default. A project skill or agent-config rule that explicitly
> supersedes `go-design-patterns` takes precedence over this one.

Detailed reference material, loaded on demand:

- `references/creation-patterns.md` — functional options (full example),
  options vs config struct, constructors, factory.
- `references/behavioral-patterns.md` — strategy, middleware/decorator,
  result type, defer cleanup, sentinel vs zero values.
- `references/resilience-and-types.md` — retry with jitter, circuit
  breaker, bulkhead, parse-don't-validate types, status types.

Read a reference file only when the summary below is not enough.

## Pattern Selection

| Need | Pattern | Reference |
|---|---|---|
| Constructor with many optional settings | Functional options | creation-patterns.md |
| Config loaded from file/env, mostly required fields | Config struct | creation-patterns.md |
| Enforce invariants at creation | Constructor returning error | creation-patterns.md |
| Pick implementation from runtime config | Factory returning interface | creation-patterns.md |
| Swap simple behavior at runtime | Strategy via function type | behavioral-patterns.md |
| Swap complex behavior at runtime | Strategy via interface | behavioral-patterns.md |
| Wrap cross-cutting concerns (log, cache, metrics) | Middleware / decorator | behavioral-patterns.md |
| Value-or-error in concurrent pipelines | `Result[T]` struct | behavioral-patterns.md |
| Transient failures of a dependency | Retry with backoff and jitter | resilience-and-types.md |
| A dependency that is down | Circuit breaker, bulkhead | resilience-and-types.md |
| Validate once, trust afterwards | Parse into a type with unexported fields | resilience-and-types.md |
| Several booleans describing one lifecycle | A status type with explicit transitions | resilience-and-types.md |

## 1. Functional Options (essentials)

```go
type Option func(*Server)

func WithAddr(addr string) Option {
    return func(s *Server) { s.addr = addr }
}

func NewServer(opts ...Option) *Server {
    s := &Server{
        addr:        ":8080", // sensible defaults first
        readTimeout: 5 * time.Second,
        logger:      slog.Default(),
    }
    for _, opt := range opts {
        opt(s)
    }
    return s
}

srv := NewServer(WithAddr(":9090"))
```

Use when: many optional parameters with sensible defaults, API evolves over
time (new options don't break callers), options need validation.
Use a plain config struct instead when most fields are required or the
configuration is deserialized from file/env.

## 2. Constructor Rules

- Every exported type with invariants needs a constructor.
- Validate required dependencies; return an error, don't panic:

```go
// ✅ Good — constructor enforces invariants
func NewUserService(repo UserRepository, logger *slog.Logger) (*UserService, error) {
    if repo == nil {
        return nil, errors.New("user service: nil repository")
    }
    return &UserService{repo: repo, logger: logger}, nil
}

// ❌ Bad — struct literal with no validation
svc := &UserService{} // nil dependencies → panic at runtime
```

## 3. Factory

Return the interface, not a concrete type. The factory is the only place
that knows about concrete implementations:

```go
func NewStore(cfg Config) (Store, error) {
    switch cfg.StoreType {
    case "redis":
        return newRedisStore(cfg.RedisAddr)
    case "memory":
        return newMemoryStore(), nil
    default:
        return nil, fmt.Errorf("unknown store type: %s", cfg.StoreType)
    }
}
```

## 4. Middleware Chain

The standard HTTP composition pattern:

```go
type Middleware func(http.Handler) http.Handler

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

handler := Chain(appHandler, Recoverer, RequestID, Logger, Auth)
```

The same shape works for any interface: stack decorators as
`cache → logging → metrics → actual repo`
(see `references/behavioral-patterns.md`).

## 5. Zero Values First

Prefer types whose zero value is useful (`sync.Mutex`, `bytes.Buffer`,
nil slices). Reach for sentinel wrappers or pointers only when the zero
value is ambiguous as an input (`nil *float64` = "not configured").

## 6. Resilience

- Every outbound call has a deadline from `ctx` (go-context owns budgets).
- Retry only what is safe to repeat, with exponential backoff and full
  jitter, a cap, and at **one** layer — nested retries multiply.
- A circuit breaker fails fast while a dependency is down; use a maintained
  implementation, and degrade (cached value, partial response) when open.
- A bulkhead (a semaphore per dependency) stops one slow dependency from
  absorbing every goroutine and connection.

## 7. Make Illegal States Unrepresentable

Parse input once into a type with unexported fields (`ParseEmail` →
`Email`), so every function that receives it can trust it. Replace
clusters of booleans (`Paid`, `Shipped`, `Cancelled`) with one status type
and methods that check the transition.

Examples for sections 6-7: `references/resilience-and-types.md`.

## Anti-Patterns to Avoid

```go
// ❌ God interface — too many methods
type Service interface {
    GetUser(ctx context.Context, id string) (*User, error)
    CreateUser(ctx context.Context, u *User) error
    DeleteUser(ctx context.Context, id string) error
    ListOrders(ctx context.Context, userID string) ([]Order, error)
    // 20 more methods...
}
// → Split into focused interfaces: UserReader, UserWriter, OrderLister

// ❌ Premature abstraction — interface for one implementation
type UserCache interface {
    Get(key string) (*User, bool)
    Set(key string, user *User)
}
// If there's only ever one implementation, use the concrete type.
// Extract an interface when a second consumer or implementation appears.

// ❌ Java-style inheritance simulation
type BaseService struct{ /* ... */ }
type UserService struct{ BaseService } // embedding is NOT inheritance
// → Use composition: UserService has a dependency, not a parent.
```

## Verification Checklist

1. Functional options used for types with optional configuration
2. Constructors validate required dependencies and return errors
3. Factory functions return interfaces, not concrete types
4. No god interfaces — each interface has 1-3 methods
5. Middleware follows `func(http.Handler) http.Handler` signature
6. Decorators wrap interfaces, not concrete types
7. `defer` used for all resource cleanup (files, connections, locks)
8. Zero values are meaningful — no unnecessary initialization
9. No premature abstractions — interfaces extracted only when needed
10. Composition used instead of embedding for code reuse
11. Outbound calls have deadlines; retries are jittered, capped and at one layer
12. Validated values and lifecycles are encoded in types, not re-checked or spread over booleans
Pliki w paczce (4)
  • SKILL.md 8 KB
  • references/behavioral-patterns.md 5 KB
  • references/creation-patterns.md 3 KB
  • references/resilience-and-types.md 4 KB

Wersje

W bazie nie ma innych skilli o nazwie go-design-patterns.

Identyczna treść występuje jeszcze w 1 innych folderach na GitHubie. Tu pokazujemy jedną, najlepiej ocenioną kopię.

Migawka bazy z 13.11.2026 · wersja paczki 5a65c1046797 (skrót SHA-256 całej paczki)

Pobrania w ostatnich 30 dniach: 0 · ranking

Zgłoś problem z tym skillem: szkodliwa treść, błędny opis albo prośba autora o usunięcie.

Podobne skille

  • 95design-patterns
    Pokazuje wzorce projektowe w Javie, jak fabryka, budowniczy, strategia czy obserwator, przy projektowaniu rozszerzalnych komponentów.
  • 100golang-patterns
    Stosuje wzorce projektowe i dobre praktyki Go: opcje funkcyjne, małe interfejsy, wstrzykiwanie zależności, wzorce współbieżności, obsługę błędów i organizację pakietów.
  • 100design-patterns
    Identyfikuje wzorce projektowe w kodzie i prowadzi refaktoryzację w ich stronę, na przykład strategy, factory method czy observer, aby zmniejszyć sprzężenie i uczynić kod rozszerzalnym.
  • 100design-patterns
    Rozpoznaje, implementuje i refaktoryzuje kod według standardowych wzorców projektowych (GoF i nowoczesnych), takich jak strategy, observer, factory i singleton.
  • 100golang-design-patterns
    Dostarcza idiomatyczne wzorce projektowe Go: functional options, API konstruktorów, unikanie init() i stanu globalnego, panic kontra error, graceful shutdown, retry i style architektury.
  • 100factory-pattern-creator
    Prawdopodobnie tworzy wzorce fabryki dla automatyzacji testów na podstawie nazwy skilla i kategorii.

Uwagi i zgłoszenia

Wiadomość trafi do Bartosza Sokolińskiego. Adres e-mail jest potrzebny tylko do odpowiedzi. Szczegóły w polityce prywatności.