Golang Patterns

affaan-m/ECC/.kiro/skills/golang-patterns

作者 affaan-mef648e01899ba3e8dc6371642deaaf64b4477775無授權條款275K 個星標收錄於 2026年10月9日更新於 2026年10月9日儲存庫4 天前更新

Go-specific design patterns and best practices including functional options, small interfaces, dependency injection, concurrency patterns, error handling, and package organization. Use when working with Go code to apply idiomatic Go patterns.

AI 產生的概覽

關於道地 Go 設計模式、併發、錯誤處理與專案結構的參考指南。

功能
此技能提供 Go 特有的設計模式與最佳實務,涵蓋函式選項、小型介面、依賴注入、併發模式、錯誤處理、套件組織以及測試模式。每個主題都附有簡短程式碼範例與所述優點,例如建構函式、工作池、context 傳遞、錯誤包裝、哨兵錯誤與表驅動測試。它產出的是參考指南與範例程式碼,而非執行任何工具。
適用情境
適用於設計 Go API 與套件、實作併發系統、規劃 Go 專案結構、撰寫道地 Go 程式碼或重構 Go 程式庫時。它面向 Go 原始檔與模組檔的相關工作。
執行需求
不隨附指令碼或工具,僅為說明性內容。套用其中的範例需要 Go 工具鏈,並熟悉所示標準函式庫套件,例如 context、sync、errors、fmt 與 testing。

Go Patterns

This skill provides comprehensive Go patterns extending common design principles with Go-specific idioms.

Functional Options

Use the functional options pattern for flexible constructor configuration:

go
type Option func(*Server)
func WithPort(port int) Option {    return func(s *Server) { s.port = port }}
func NewServer(opts ...Option) *Server {    s := &Server{port: 8080}    for _, opt := range opts {        opt(s)    }    return s}

Benefits:

  • Backward compatible API evolution
  • Optional parameters with defaults
  • Self-documenting configuration

Small Interfaces

Define interfaces where they are used, not where they are implemented.

Principle: Accept interfaces, return structs

go
// Good: Small, focused interface defined at point of usetype UserStore interface {    GetUser(id string) (*User, error)}
func ProcessUser(store UserStore, id string) error {    user, err := store.GetUser(id)    // ...}

Benefits:

  • Easier testing and mocking
  • Loose coupling
  • Clear dependencies

Dependency Injection

Use constructor functions to inject dependencies:

go
func NewUserService(repo UserRepository, logger Logger) *UserService {    return &UserService{        repo:   repo,        logger: logger,    }}

Pattern:

  • Constructor functions (New* prefix)
  • Explicit dependencies as parameters
  • Return concrete types
  • Validate dependencies in constructor

Concurrency Patterns

Worker Pool

go
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 <- processJob(job)            }        }()    }    wg.Wait()    close(results)}

Context Propagation

Always pass context as first parameter:

go
func FetchUser(ctx context.Context, id string) (*User, error) {    // Check context cancellation    select {    case <-ctx.Done():        return nil, ctx.Err()    default:    }    // ... fetch logic}

Error Handling

Error Wrapping

go
if err != nil {    return fmt.Errorf("failed to fetch user %s: %w", id, err)}

Custom Errors

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

Sentinel Errors

go
var (    ErrNotFound = errors.New("not found")    ErrInvalid  = errors.New("invalid input"))
// Check with errors.Isif errors.Is(err, ErrNotFound) {    // handle not found}

Package Organization

Structure

project/├── cmd/              # Main applications│   └── server/│       └── main.go├── internal/         # Private application code│   ├── domain/       # Business logic│   ├── handler/      # HTTP handlers│   └── repository/   # Data access└── pkg/              # Public libraries

Naming Conventions

  • Package names: lowercase, single word
  • Avoid stutter: user.User not user.UserModel
  • Use internal/ for private code
  • Keep main package minimal

Testing Patterns

Table-Driven Tests

go
func TestValidate(t *testing.T) {    tests := []struct {        name    string        input   string        wantErr bool    }{        {"valid", "[email protected]", false},        {"invalid", "not-an-email", true},    }
    for _, tt := range tests {        t.Run(tt.name, func(t *testing.T) {            err := Validate(tt.input)            if (err != nil) != tt.wantErr {                t.Errorf("got error %v, wantErr %v", err, tt.wantErr)            }        })    }}

Test Helpers

go
func testDB(t *testing.T) *sql.DB {    t.Helper()    db, err := sql.Open("sqlite3", ":memory:")    if err != nil {        t.Fatalf("failed to open test db: %v", err)    }    t.Cleanup(func() { db.Close() })    return db}

When to Use This Skill

  • Designing Go APIs and packages
  • Implementing concurrent systems
  • Structuring Go projects
  • Writing idiomatic Go code
  • Refactoring Go codebases

來源與署名

來源:affaan-m/ECC位於.kiro/skills/golang-patterns提交ef648e0

授權條款: 無授權條款

內容歸原作者所有。SourceWeft 從公開儲存庫中收錄這些內容。

檢舉或申請下架