golang について
golang は、慣用的な Go コードの作成とレビューを支援するスキルです。並行処理、エラー処理、インターフェース、構成、テスト、モジュール管理を扱います。
主な機能
- 01Go の並行処理パターンの適用
- 02明示的なエラー処理
- 03小さなインターフェース設計
- 04Go プロジェクトの構成
- 05テーブル駆動テストの作成
- 06Go モジュールの管理
活用シーン
- 01Go コードへの並行処理の追加
- 02Go のエラー処理のレビュー
- 03Go プロジェクトのインターフェース設計
インストール
コマンドをコピーしてターミナルで実行します。
$
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個)
- エラーを明示的に処理します
- キャンセルにはコンテキストを使用します
- グローバル状態を避けます
例
入力:「これに並行処理を追加して」 **アクション:**並列化できる作業を特定し、適切な同期処理を伴うゴルーチンを追加して、エラーを処理します
入力:「この Go コードをレビューして」 **アクション:**エラー処理、インターフェース設計、並行処理の安全性を確認します
コメント
Markdown 対応