mcpField
G
golang

golang

github.com/htlin222开发7838 次安装3 周前更新
代码仓库

关于 golang

golang 是用于编写惯用 Go 代码和审查 Go 代码的技能,涵盖并发、错误处理、接口、项目结构、测试与模块管理。

主要功能

  1. 01应用 Go 并发模式
  2. 02显式处理错误
  3. 03设计精简接口
  4. 04组织 Go 项目结构
  5. 05编写表驱动测试
  6. 06管理 Go 模块

适用场景

  1. 01为 Go 代码添加并发
  2. 02审查 Go 错误处理
  3. 03为 Go 项目设计接口

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/htlin222/dotfiles --skill golang

安装后在 Claude Code 中输入/golang确认已加载。

详细介绍

Go 开发

编写简洁、并发且符合 Go 惯用风格的代码。

使用场景

  • 编写 Go 代码
  • 并发模式
  • 性能优化
  • 接口设计
  • Go 模块管理

Go 模式

并发
// Worker pool pattern
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 <- process(job)
            }
        }()
    }
    wg.Wait()
    close(results)
}

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

    req, _ := http.NewRequestWithContext(ctx, "GET", url, nil)
    resp, err := http.DefaultClient.Do(req)
    if err != nil {
        return nil, err
    }
    defer resp.Body.Close()
    return io.ReadAll(resp.Body)
}
错误处理
// Custom errors with context
type ValidationError struct {
    Field   string
    Message string
}

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

// Error wrapping
if err != nil {
    return fmt.Errorf("failed to process user %d: %w", userID, err)
}
接口
// Small, focused interfaces
type Reader interface {
    Read(p []byte) error
}

type Writer interface {
    Write(p []byte) error
}

// Composition
type ReadWriter interface {
    Reader
    Writer
}

项目结构

project/
├── cmd/
│   └── app/
│       └── main.go
├── internal/
│   ├── handler/
│   └── service/
├── pkg/
│   └── utils/
├── go.mod
└── go.sum

测试

func TestProcess(t *testing.T) {
    tests := []struct {
        name    string
        input   string
        want    string
        wantErr bool
    }{
        {"valid input", "hello", "HELLO", false},
        {"empty input", "", "", true},
    }

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

最佳实践

  • 优先使用组合,而非继承
  • 保持接口精简(1-3 个方法)
  • 显式处理错误
  • 使用 context 取消操作
  • 避免全局状态

示例

输入:“为此添加并发” **操作:**找出可并行执行的工作,添加 goroutine 并进行适当同步,处理错误

输入:“审查这段 Go 代码” **操作:**检查错误处理、接口设计和并发安全

评论

支持 Markdown