Skip to content
Development
Skill

/golang-patterns

编写稳健、高效且易于维护的 Go 应用程序的惯用模式、最佳实践和约定。

From plugin
everything-claude-code
1.8k59 skills15 agents35 commands6 hooks
Install
$ npx -y skills add xu-xiang/everything-claude-code-zh --skill golang-patterns --agent claude-code

How it fires

How this skill gets triggered: by you, by Claude, or both.

  • Fires itselfAuto-invocation. Claude auto-loads it when your prompt matches the work.Auto-invocation is when the right skill fires by itself at the right moment, driven by a FLOW.md router and a hook, instead of you invoking it by name. It is the difference between a skill being installed and a skill actually getting used.Read the full definition →
  • You can call itInvoke it directly when you want it.
  • Slash command/golang-patterns

Context preview

The summary Claude sees to decide when to auto-load this skill.

编写稳健、高效且易于维护的 Go 应用程序的惯用模式、最佳实践和约定。

SKILL.md

golang-patterns.SKILL.md
name: golang-patterns
description: 编写稳健、高效且易于维护的 Go 应用程序的惯用模式、最佳实践和约定。
origin: ECC

Go 开发模式 (Go Development Patterns)

构建稳健、高效且易于维护的应用程序的惯用 Go 模式和最佳实践。

激活时机

  • 编写新的 Go 代码时
  • 评审 Go 代码时
  • 重构现有 Go 代码时
  • 设计 Go 包/模块时

核心原则

1. 简单与清晰

Go 倾向于简单而非巧妙。代码应当直观且易于阅读。

// 推荐:清晰且直接
func GetUser(id string) (*User, error) {
    user, err := db.FindUser(id)
    if err != nil {
        return nil, fmt.Errorf("get user %s: %w", id, err)
    }
    return user, nil
}

// 不推荐:过于巧妙
func GetUser(id string) (*User, error) {
    return func() (*User, error) {
        if u, e := db.FindUser(id); e == nil {
            return u, nil
        } else {
            return nil, e
        }
    }()
}

2. 使“零值”有用

设计类型时,使其零值(Zero Value)在无需显式初始化的情况下即可立即使用。

// 推荐:零值即有用
type Counter struct {
    mu    sync.Mutex
    count int // 零值为 0,可直接使用
}

func (c *Counter) Inc() {
    c.mu.Lock()
    c.count++
    c.mu.Unlock()
}

// 推荐:bytes.Buffer 的零值即可工作
var buf bytes.Buffer
buf.WriteString("hello")

// 不推荐:需要显式初始化
type BadCounter struct {
    counts map[string]int // nil map 会引发 panic
}

3. 接受接口,返回结构体

函数应当接受接口(Interface)参数并返回具体类型(Concrete types/Structs)。

// 推荐:接受接口,返回具体类型
func ProcessData(r io.Reader) (*Result, error) {
    data, err := io.ReadAll(r)
    if err != nil {
        return nil, err
    }
    return &Result{Data: data}, nil
}

// 不推荐:返回接口(无谓地隐藏了实现细节)
func ProcessData(r io.Reader) (io.Reader, error) {
    // ...
}

错误处理模式 (Error Handling Patterns)

带有上下文的错误包装

// 推荐:使用上下文包装错误
func LoadConfig(path string) (*Config, error) {
    data, err := os.ReadFile(path)
    if err != nil {
        return nil, fmt.Errorf("load config %s: %w", path, err)
    }

    var cfg Config
    if err := json.Unmarshal(data, &cfg); err != nil {
        return nil, fmt.Errorf("parse config %s: %w", path, err)
    }

    return &cfg, nil
}

自定义错误类型

// 定义领域特定的错误
type ValidationError struct {
    Field   string
    Message string
}

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

// 常见情况的哨兵错误 (Sentinel errors)
var (
    ErrNotFound     = errors.New("resource not found")
    ErrUnauthorized = errors.New("unauthorized")
    ErrInvalidInput = errors.New("invalid input")
)

使用 errors.Is 和 errors.As 进行错误检查

func HandleError(err error) {
    // 检查特定错误
    if errors.Is(err, sql.ErrNoRows) {
        log.Println("No records found")
        return
    }

    // 检查错误类型
    var validationErr *ValidationError
    if errors.As(err, &validationErr) {
        log.Printf("Validation error on field %s: %s",
            validationErr.Field, validationErr.Message)
        return
    }

    // 未知错误
    log.Printf("Unexpected error: %v", err)
}

绝不忽略错误

// 不推荐:使用空白标识符忽略错误
result, _ := doSomething()

// 推荐:处理错误,或显式说明为何忽略是安全的
result, err := doSomething()
if err != nil {
    return err
}

// 可接受:当错误确实无关紧要时(少见)
_ = writer.Close() // 尽力而为的清理,错误已在别处记录

并发模式 (Concurrency Patterns)

工作池 (Worker Pool)

func WorkerPool(jobs <-chan Job, results chan<- Result, numWorkers int) {
    var wg sync.WaitGroup

    for i := 0; i < numWorkers; i++ {
        wg.Add(1)
        go func() {
            defer wg.Done()
            for job := range jobs {
                results <- process(job)
            }
        }()
    }

    wg.Wait()
    close(results)
}

使用 Context 处理取消和超时

func FetchWithTimeout(ctx context.Context, url string) ([]byte, error) {
    ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
    defer cancel()

    req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
    if err != nil {
        return nil, fmt.Errorf("create request: %w", err)
    }

    resp, err := http.DefaultClient.Do(req)
    if err != nil {
        return nil, fmt.Errorf("fetch %s: %w", url, err)
    }
    defer resp.Body.Close()

    return io.ReadAll(resp.Body)
}

优雅停机 (Graceful Shutdown)

func GracefulShutdown(server *http.Server) {
    quit := make(chan os.Signal, 1)
    signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)

    <-quit
    log.Println("Shutting down server...")

    ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
    defer cancel()

    if err := server.Shutdown(ctx); err != nil {
        log.Fatalf("Server forced to shutdown: %v", err)
    }

    log.Println("Server exited")
}

使用 errgroup 协调协程

import "golang.org/x/sync/errgroup"

func FetchAll(ctx context.Context, urls []string) ([][]byte, error) {
    g, ctx := errgroup.WithContext(ctx)
    results := make([][]byte, len(urls))

    for i, url := range urls {
        i, url := i, url // 捕获循环变量
        g.Go(func() error {
            data, err := FetchWithTimeout(ctx, url)
            if err != nil {
                return err
            }
            results[i] = data
            return nil
        })
    }

    if err := g.Wait(); err != nil {
        return nil, err
    }
    return results, nil
}

避免协程泄漏 (Goroutine Leaks)

// 不推荐:如果 context 被取消,协程会泄漏
func leakyFetch(ctx context.Context, url string) <-chan []byte {
    ch := make(chan []byte)
    go func() {
        data, _ := fetch(url)
        ch <- data // 如果没有接收者,将永久阻塞
    }()
    return ch
}

// 推荐:正确处理取消
func safeFetch(ctx context.Context, url string) <-chan []byte {
    ch := make(chan []byte, 1) // 使用缓冲通道
    go func() {
        data, err := fetch(url)
        if err != nil {
            return
        }
        select {
        case ch <- data:
        case <-ctx.Done():
        }
    }()
    return ch
}

接口设计 (Interface Design)

小而专注的接口

// 推荐:单方法接口
type Reader interface {
    Read(p []byte) (n int, err error)
}

type Writer interface {
    Write(p []byte) (n int, err error)
}

type Closer interface {
    Close() error
}

// 根据需要组合接口
type ReadWriteCloser interface {
    Reader
    Writer
    Closer
}

在使用处定义接口

// 在消费者包中定义,而不是在提供者包中
package service

//
Read more
Ships witheverything-claude-code

🌐 Language / 语言 / 語言 为 AI 智能体(Agent)框架打造的性能优化系统。源自 Anthropic 黑客松获胜作品。 这不仅仅是配置文件。它是一个完整的系统:包含技能(Skills)、本能(Instincts)、内存优化、持续学习、安全扫描以及研究优先的开发模式。这些生产级的智能体(Agents)、钩子(Hooks)、命令(Commands)、规则(Rules)以及 MCP 配置,是在构建真实产品的 10 个多月高强度日常使用中演化而来的。 适用于 Claude Code, Codex,

Get the whole plugin