SKILL·7768BA

go-design-patterns

eduardo-sl
更新于 8 days ago
64
9
64
在 GitHub 上查看
aidesign

关于

This skill provides idiomatic Go implementations of common design patterns like functional options, builder, factory, and strategy patterns. Use it when you need guidance on structuring Go code with patterns adapted to Go's type system and composition philosophy. It specifically excludes interface design, package layout, and concurrency topics which are covered by other skills.

快速安装

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 是一个 Claude Skill,作者为 eduardo-sl。Skill 将 Claude 按需加载的说明和资源打包,让 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 是一个 TypeScript 优先的构建工具,可将本地 Markdown/MDX 文件转换为类型安全的数据集合。它专为构建博客、文档站和内容密集型 Vite+React 应用而设计,提供基于 Zod 的自动模式验证。该工具涵盖从 Vite 插件配置、MDX 编译到生产环境部署的完整工作流。

查看技能
polymarket

这个Claude Skill为开发者提供完整的Polymarket预测市场开发支持,涵盖API调用、交易执行和市场数据分析。关键特性包括实时WebSocket数据流,可监控实时交易、订单和市场动态。开发者可用它构建预测市场应用、实施交易策略并集成实时市场预测功能。

查看技能
creating-opencode-plugins

该Skill帮助开发者创建OpenCode插件,用于接入命令、文件、LSP等25+种事件。它提供了插件结构、事件API规范和JavaScript/TypeScript实现模式,适合需要拦截操作、扩展功能或自定义事件处理的场景。开发者可通过它快速构建响应式模块来增强OpenCode AI助手的能力。

查看技能
sglang

SGLang是一个专为LLM设计的高性能推理框架,特别适用于需要结构化输出的场景。它通过RadixAttention前缀缓存技术,在处理JSON、正则表达式、工具调用等具有重复前缀的复杂工作流时,能实现极速生成。如果你正在构建智能体或多轮对话系统,并追求远超vLLM的推理性能,SGLang是理想选择。

查看技能