MCP HubMCP Hub
SKILL·7768BA

go-design-patterns

eduardo-sl
업데이트됨 22 days ago
4 조회
68
9
68
GitHub에서 보기
메타aidesign

정보

이 스킬은 함수형 옵션, 빌더, 팩토리, 전략 패턴과 같은 일반적인 디자인 패턴의 관용적 Go 구현을 제공합니다. Go의 타입 시스템과 조합 철학에 맞게 패턴을 적용하여 Go 코드를 구조화할 때 가이드가 필요할 경우 사용하세요. 다른 스킬에서 다루는 인터페이스 설계, 패키지 레이아웃, 동시성 관련 주제는 명시적으로 제외됩니다.

빠른 설치

Claude Code

추천
기본
npx skills add eduardo-sl/go-agent-skills -a claude-code
플러그인 명령대체
/plugin add https://github.com/eduardo-sl/go-agent-skills
Git 클론대체
git clone https://github.com/eduardo-sl/go-agent-skills.git ~/.claude/skills/go-design-patterns

Claude Code에서 이 명령을 복사하여 붙여넣어 스킬을 설치하세요

문서

Go Design Patterns

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

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.

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

Pattern Selection

NeedPatternReference
Constructor with many optional settingsFunctional optionscreation-patterns.md
Config loaded from file/env, mostly required fieldsConfig structcreation-patterns.md
Enforce invariants at creationConstructor returning errorcreation-patterns.md
Pick implementation from runtime configFactory returning interfacecreation-patterns.md
Swap simple behavior at runtimeStrategy via function typebehavioral-patterns.md
Swap complex behavior at runtimeStrategy via interfacebehavioral-patterns.md
Wrap cross-cutting concerns (log, cache, metrics)Middleware / decoratorbehavioral-patterns.md
Value-or-error in concurrent pipelinesResult[T] structbehavioral-patterns.md

1. Functional Options (essentials)

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:
// ✅ 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:

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:

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").

Anti-Patterns to Avoid

// ❌ 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

GitHub 저장소

eduardo-sl/go-agent-skills
경로: skills/(architecture)/go-design-patterns
0
FAQ

자주 묻는 질문

go-design-patterns Skill이란 무엇인가요?

go-design-patterns은(는) eduardo-sl이(가) 만든 Claude Skill입니다. Skill은 Claude가 필요할 때 불러오는 지침과 리소스를 묶어 추가 프롬프트 없이 go-design-patterns 관련 작업을 수행할 수 있게 합니다.

go-design-patterns은(는) 어떻게 설치하나요?

이 페이지의 설치 명령을 사용하세요. go-design-patterns을(를) Claude Code 플러그인으로 추가하거나 저장소를 skills 디렉터리에 복제한 다음 Claude를 다시 시작해 Skill을 불러옵니다.

go-design-patterns은(는) 어떤 카테고리에 속하나요?

go-design-patterns은(는) 메타 카테고리에 속합니다.

go-design-patterns은(는) 무료로 사용할 수 있나요?

네. go-design-patterns은(는) AIMCP에 등록되어 있으며 무료로 설치할 수 있습니다.

연관 스킬

content-collections
메타

이 스킬은 콘텐츠 콜렉션(Content Collections)을 위한 프로덕션 검증된 설정을 제공합니다. 콘텐츠 콜렉션은 Markdown/MDX 파일을 Zod 검증이 포함된 타입 안전한 데이터 콜렉션으로 변환해주는 TypeScript 최우선 도구입니다. 블로그, 문서 사이트 또는 콘텐츠 중심의 Vite + React 애플리케이션을 구축할 때 타입 안전성과 자동 콘텐츠 검증을 보장하기 위해 사용하세요. Vite 플러그인 구성과 MDX 컴파일부터 배포 최적화 및 스키마 검증에 이르기까지 모든 것을 다룹니다.

스킬 보기
polymarket
메타

이 스킬은 개발자들이 Polymarket 예측 시장 플랫폼을 활용한 애플리케이션을 구축할 수 있도록 지원하며, 거래 및 시장 데이터를 위한 API 통합 기능을 포함합니다. 또한 WebSocket을 통한 실시간 데이터 스트리밍을 제공하여 실시간 거래와 시장 활동을 모니터링할 수 있습니다. 이를 통해 거래 전략을 구현하거나 실시간 시장 업데이트를 처리하는 도구를 생성하는 데 활용할 수 있습니다.

스킬 보기
creating-opencode-plugins
메타

이 스킬은 개발자들이 명령어, 파일, LSP 작업 등 25개 이상의 이벤트 유형에 연결되는 OpenCode 플러그인을 만들 수 있도록 돕습니다. JavaScript/TypeScript 모듈을 위한 플러그인 구조, 이벤트 API 명세, 구현 패턴을 제공합니다. OpenCode AI 어시스턴트의 라이프사이클을 사용자 정의 이벤트 기반 로직으로 가로채거나, 모니터링하거나, 확장해야 할 때 사용하세요.

스킬 보기
sglang
메타

SGLang은 RadixAttention 프리픽스 캐싱을 활용하여 JSON, 정규식, 에이전트 워크플로우를 위한 고속 구조화 생성에 특화된 고성능 LLM 서빙 프레임워크입니다. 특히 반복되는 프리픽스가 있는 작업에서 상당히 빠른 추론 속도를 제공하여 복잡한 구조화 출력 및 다중 턴 대화에 이상적입니다. 제약 디코딩이 필요하거나 광범위한 프리픽스 공유가 있는 애플리케이션을 구축할 때는 vLLM과 같은 대안보다 SGLang을 선택하십시오.

스킬 보기