{"slug":"golang-patterns","title":"golang-patterns","summary":"Idiomatic Go patterns, best practices, and conventions for building robust, efficient, and maintainable Go applications. Use when writing or reviewing Go code and idiomatic structure or conventions are in question.","platform":"Claude","tags":[],"authorName":"LLM Mart","authorSlug":"llm-mart","score":0,"source":"github","price":null,"verified":false,"createdAt":"2026-12-02T16:53:40.612369Z","repo":{"url":"https://github.com/beginwithu/agent-skills","stars":11,"forks":2,"license":"MIT","updatedAt":"2026-12-02T16:37:11Z"},"bodyHtml":"<hr>\n<h2>name: golang-patterns\ndescription: Idiomatic Go patterns, best practices, and conventions for building robust, efficient, and maintainable Go applications. Use when writing or reviewing Go code and idiomatic structure or conventions are in question.\nmetadata:\norigin: ECC</h2>\n<h1>Go Development Patterns</h1>\n<p>Idiomatic Go patterns and best practices for building robust, efficient, and maintainable applications.</p>\n<h2>When to Activate</h2>\n<ul>\n<li>Writing new Go code</li>\n<li>Reviewing Go code</li>\n<li>Refactoring existing Go code</li>\n<li>Designing Go packages/modules</li>\n</ul>\n<h2>Core Principles</h2>\n<h3>1. Simplicity and Clarity</h3>\n<p>Go favors simplicity over cleverness. Code should be obvious and easy to read.</p>\n<pre><code>// Good: Clear and direct\nfunc GetUser(id string) (*User, error) {\n    user, err := db.FindUser(id)\n    if err != nil {\n        return nil, fmt.Errorf(\"get user %s: %w\", id, err)\n    }\n    return user, nil\n}\n\n// Bad: Overly clever\nfunc GetUser(id string) (*User, error) {\n    return func() (*User, error) {\n        if u, e := db.FindUser(id); e == nil {\n            return u, nil\n        } else {\n            return nil, e\n        }\n    }()\n}\n</code></pre>\n<h3>2. Make the Zero Value Useful</h3>\n<p>Design types so their zero value is immediately usable without initialization.</p>\n<pre><code>// Good: Zero value is useful\ntype Counter struct {\n    mu    sync.Mutex\n    count int // zero value is 0, ready to use\n}\n\nfunc (c *Counter) Inc() {\n    c.mu.Lock()\n    c.count++\n    c.mu.Unlock()\n}\n\n// Good: bytes.Buffer works with zero value\nvar buf bytes.Buffer\nbuf.WriteString(\"hello\")\n\n// Bad: Requires initialization\ntype BadCounter struct {\n    counts map[string]int // nil map will panic\n}\n</code></pre>\n<h3>3. Accept Interfaces, Return Structs</h3>\n<p>Functions should accept interface parameters and return concrete types.</p>\n<pre><code>// Good: Accepts interface, returns concrete type\nfunc ProcessData(r io.Reader) (*Result, error) {\n    data, err := io.ReadAll(r)\n    if err != nil {\n        return nil, err\n    }\n    return &amp;Result{Data: data}, nil\n}\n\n// Bad: Returns interface (hides implementation details unnecessarily)\nfunc ProcessData(r io.Reader) (io.Reader, error) {\n    // ...\n}\n</code></pre>\n<h2>Error Handling Patterns</h2>\n<h3>Error Wrapping with Context</h3>\n<pre><code>// Good: Wrap errors with context\nfunc LoadConfig(path string) (*Config, error) {\n    data, err := os.ReadFile(path)\n    if err != nil {\n        return nil, fmt.Errorf(\"load config %s: %w\", path, err)\n    }\n\n    var cfg Config\n    if err := json.Unmarshal(data, &amp;cfg); err != nil {\n        return nil, fmt.Errorf(\"parse config %s: %w\", path, err)\n    }\n\n    return &amp;cfg, nil\n}\n</code></pre>\n<h3>Custom Error Types</h3>\n<pre><code>// Define domain-specific errors\ntype ValidationError struct {\n    Field   string\n    Message string\n}\n\nfunc (e *ValidationError) Error() string {\n    return fmt.Sprintf(\"validation failed on %s: %s\", e.Field, e.Message)\n}\n\n// Sentinel errors for common cases\nvar (\n    ErrNotFound     = errors.New(\"resource not found\")\n    ErrUnauthorized = errors.New(\"unauthorized\")\n    ErrInvalidInput = errors.New(\"invalid input\")\n)\n</code></pre>\n<h3>Error Checking with errors.Is and errors.As</h3>\n<pre><code>func HandleError(err error) {\n    // Check for specific error\n    if errors.Is(err, sql.ErrNoRows) {\n        log.Println(\"No records found\")\n        return\n    }\n\n    // Check for error type\n    var validationErr *ValidationError\n    if errors.As(err, &amp;validationErr) {\n        log.Printf(\"Validation error on field %s: %s\",\n            validationErr.Field, validationErr.Message)\n        return\n    }\n\n    // Unknown error\n    log.Printf(\"Unexpected error: %v\", err)\n}\n</code></pre>\n<h3>Never Ignore Errors</h3>\n<pre><code>// Bad: Ignoring error with blank identifier\nresult, _ := doSomething()\n\n// Good: Handle or explicitly document why it's safe to ignore\nresult, err := doSomething()\nif err != nil {\n    return err\n}\n\n// Acceptable: When error truly doesn't matter (rare)\n_ = writer.Close() // Best-effort cleanup, error logged elsewhere\n</code></pre>\n<h2>Concurrency Patterns</h2>\n<h3>Worker Pool</h3>\n<pre><code>func WorkerPool(jobs &lt;-chan Job, results chan&lt;- Result, numWorkers int) {\n    var wg sync.WaitGroup\n\n    for i := 0; i &lt; numWorkers; i++ {\n        wg.Add(1)\n        go func() {\n            defer wg.Done()\n            for job := range jobs {\n                results &lt;- process(job)\n            }\n        }()\n    }\n\n    wg.Wait()\n    close(results)\n}\n</code></pre>\n<h3>Context for Cancellation and Timeouts</h3>\n<pre><code>func FetchWithTimeout(ctx context.Context, url string) ([]byte, error) {\n    ctx, cancel := context.WithTimeout(ctx, 5*time.Second)\n    defer cancel()\n\n    req, err := http.NewRequestWithContext(ctx, \"GET\", url, nil)\n    if err != nil {\n        return nil, fmt.Errorf(\"create request: %w\", err)\n    }\n\n    resp, err := http.DefaultClient.Do(req)\n    if err != nil {\n        return nil, fmt.Errorf(\"fetch %s: %w\", url, err)\n    }\n    defer resp.Body.Close()\n\n    return io.ReadAll(resp.Body)\n}\n</code></pre>\n<h3>Graceful Shutdown</h3>\n<pre><code>func GracefulShutdown(server *http.Server) {\n    quit := make(chan os.Signal, 1)\n    signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)\n\n    &lt;-quit\n    log.Println(\"Shutting down server...\")\n\n    ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)\n    defer cancel()\n\n    if err := server.Shutdown(ctx); err != nil {\n        log.Fatalf(\"Server forced to shutdown: %v\", err)\n    }\n\n    log.Println(\"Server exited\")\n}\n</code></pre>\n<h3>errgroup for Coordinated Goroutines</h3>\n<pre><code>import \"golang.org/x/sync/errgroup\"\n\nfunc FetchAll(ctx context.Context, urls []string) ([][]byte, error) {\n    g, ctx := errgroup.WithContext(ctx)\n    results := make([][]byte, len(urls))\n\n    for i, url := range urls {\n        i, url := i, url // Capture loop variables\n        g.Go(func() error {\n            data, err := FetchWithTimeout(ctx, url)\n            if err != nil {\n                return err\n            }\n            results[i] = data\n            return nil\n        })\n    }\n\n    if err := g.Wait(); err != nil {\n        return nil, err\n    }\n    return results, nil\n}\n</code></pre>\n<h3>Avoiding Goroutine Leaks</h3>\n<pre><code>// Bad: Goroutine leak if context is cancelled\nfunc leakyFetch(ctx context.Context, url string) &lt;-chan []byte {\n    ch := make(chan []byte)\n    go func() {\n        data, _ := fetch(url)\n        ch &lt;- data // Blocks forever if no receiver\n    }()\n    return ch\n}\n\n// Good: Properly handles cancellation\nfunc safeFetch(ctx context.Context, url string) &lt;-chan []byte {\n    ch := make(chan []byte, 1) // Buffered channel\n    go func() {\n        data, err := fetch(url)\n        if err != nil {\n            return\n        }\n        select {\n        case ch &lt;- data:\n        case &lt;-ctx.Done():\n        }\n    }()\n    return ch\n}\n</code></pre>\n<h2>Interface Design</h2>\n<h3>Small, Focused Interfaces</h3>\n<pre><code>// Good: Single-method interfaces\ntype Reader interface {\n    Read(p []byte) (n int, err error)\n}\n\ntype Writer interface {\n    Write(p []byte) (n int, err error)\n}\n\ntype Closer interface {\n    Close() error\n}\n\n// Compose interfaces as needed\ntype ReadWriteCloser interface {\n    Reader\n    Writer\n    Closer\n}\n</code></pre>\n<h3>Define Interfaces Where They're Used</h3>\n<pre><code>// In the consumer package, not the provider\npackage service\n\n// UserStore defines what this service needs\ntype UserStore interface {\n    GetUser(id string) (*User, error)\n    SaveUser(user *User) error\n}\n\ntype Service struct {\n    store UserStore\n}\n\n// Concrete implementation can be in another package\n// It doesn't need to know about this interface\n</code></pre>\n<h3>Optional Behavior with Type Assertions</h3>\n<pre><code>type Flusher interface {\n    Flush() error\n}\n\nfunc WriteAndFlush(w io.Writer, data []byte) error {\n    if _, err := w.Write(data); err != nil {\n        return err\n    }\n\n    // Flush if supported\n    if f, ok := w.(Flusher); ok {\n        return f.Flush()\n    }\n    return nil\n}\n</code></pre>\n<h2>Package Organization</h2>\n<h3>Standard Project Layout</h3>\n<pre><code>myproject/\n├── cmd/\n│   └── myapp/\n│       └── main.go           # Entry point\n├── internal/\n│   ├── handler/              # HTTP handlers\n│   ├── service/              # Business logic\n│   ├── repository/           # Data access\n│   └── config/               # Configuration\n├── pkg/\n│   └── client/               # Public API client\n├── api/\n│   └── v1/                   # API definitions (proto, OpenAPI)\n├── testdata/                 # Test fixtures\n├── go.mod\n├── go.sum\n└── Makefile\n</code></pre>\n<h3>Package Naming</h3>\n<pre><code>// Good: Short, lowercase, no underscores\npackage http\npackage json\npackage user\n\n// Bad: Verbose, mixed case, or redundant\npackage httpHandler\npackage json_parser\npackage userService // Redundant 'Service' suffix\n</code></pre>\n<h3>Avoid Package-Level State</h3>\n<pre><code>// Bad: Global mutable state\nvar db *sql.DB\n\nfunc init() {\n    db, _ = sql.Open(\"postgres\", os.Getenv(\"DATABASE_URL\"))\n}\n\n// Good: Dependency injection\ntype Server struct {\n    db *sql.DB\n}\n\nfunc NewServer(db *sql.DB) *Server {\n    return &amp;Server{db: db}\n}\n</code></pre>\n<h2>Struct Design</h2>\n<h3>Functional Options Pattern</h3>\n<pre><code>type Server struct {\n    addr    string\n    timeout time.Duration\n    logger  *log.Logger\n}\n\ntype Option func(*Server)\n\nfunc WithTimeout(d time.Duration) Option {\n    return func(s *Server) {\n        s.timeout = d\n    }\n}\n\nfunc WithLogger(l *log.Logger) Option {\n    return func(s *Server) {\n        s.logger = l\n    }\n}\n\nfunc NewServer(addr string, opts ...Option) *Server {\n    s := &amp;Server{\n        addr:    addr,\n        timeout: 30 * time.Second, // default\n        logger:  log.Default(),    // default\n    }\n    for _, opt := range opts {\n        opt(s)\n    }\n    return s\n}\n\n// Usage\nserver := NewServer(\":8080\",\n    WithTimeout(60*time.Second),\n    WithLogger(customLogger),\n)\n</code></pre>\n<h3>Embedding for Composition</h3>\n<pre><code>type Logger struct {\n    prefix string\n}\n\nfunc (l *Logger) Log(msg string) {\n    fmt.Printf(\"[%s] %s\\n\", l.prefix, msg)\n}\n\ntype Server struct {\n    *Logger // Embedding - Server gets Log method\n    addr    string\n}\n\nfunc NewServer(addr string) *Server {\n    return &amp;Server{\n        Logger: &amp;Logger{prefix: \"SERVER\"},\n        addr:   addr,\n    }\n}\n\n// Usage\ns := NewServer(\":8080\")\ns.Log(\"Starting...\") // Calls embedded Logger.Log\n</code></pre>\n<h2>Memory and Performance</h2>\n<h3>Preallocate Slices When Size is Known</h3>\n<pre><code>// Bad: Grows slice multiple times\nfunc processItems(items []Item) []Result {\n    var results []Result\n    for _, item := range items {\n        results = append(results, process(item))\n    }\n    return results\n}\n\n// Good: Single allocation\nfunc processItems(items []Item) []Result {\n    results := make([]Result, 0, len(items))\n    for _, item := range items {\n        results = append(results, process(item))\n    }\n    return results\n}\n</code></pre>\n<h3>Use sync.Pool for Frequent Allocations</h3>\n<pre><code>var bufferPool = sync.Pool{\n    New: func() interface{} {\n        return new(bytes.Buffer)\n    },\n}\n\nfunc ProcessRequest(data []byte) []byte {\n    buf := bufferPool.Get().(*bytes.Buffer)\n    defer func() {\n        buf.Reset()\n        bufferPool.Put(buf)\n    }()\n\n    buf.Write(data)\n    // Process...\n\n    // buf.Bytes() aliases the pooled buffer, which the deferred Put hands\n    // to the next Get. Copy before returning, or callers race with reuse.\n    return bytes.Clone(buf.Bytes()) // Go 1.20+; else append([]byte(nil), buf.Bytes()...)\n}\n</code></pre>\n<p>Never return or retain <code>buf.Bytes()</code> from a pooled buffer past <code>Put</code>: copy it, or let the caller pass in an <code>io.Writer</code> so no copy is needed.</p>\n<h3>Avoid String Concatenation in Loops</h3>\n<pre><code>// Bad: Creates many string allocations\nfunc join(parts []string) string {\n    var result string\n    for _, p := range parts {\n        result += p + \",\"\n    }\n    return result\n}\n\n// Good: Single allocation with strings.Builder\nfunc join(parts []string) string {\n    var sb strings.Builder\n    for i, p := range parts {\n        if i &gt; 0 {\n            sb.WriteString(\",\")\n        }\n        sb.WriteString(p)\n    }\n    return sb.String()\n}\n\n// Best: Use standard library\nfunc join(parts []string) string {\n    return strings.Join(parts, \",\")\n}\n</code></pre>\n<h2>Go Tooling Integration</h2>\n<h3>Essential Commands</h3>\n<pre><code># Build and run\ngo build ./...\ngo run ./cmd/myapp\n\n# Testing\ngo test ./...\ngo test -race ./...\ngo test -cover ./...\n\n# Static analysis\ngo vet ./...\nstaticcheck ./...\ngolangci-lint run\n\n# Module management\ngo mod tidy\ngo mod verify\n\n# Formatting\ngofmt -w .\ngoimports -w .\n</code></pre>\n<h3>Recommended Linter Configuration (.golangci.yml)</h3>\n<pre><code>linters:\n  enable:\n    - errcheck\n    - gosimple\n    - govet\n    - ineffassign\n    - staticcheck\n    - unused\n    - gofmt\n    - goimports\n    - misspell\n    - unconvert\n    - unparam\n\nlinters-settings:\n  errcheck:\n    check-type-assertions: true\n  govet:\n    enable:\n      - shadow\n\nissues:\n  exclude-use-default: false\n</code></pre>\n<h2>Quick Reference: Go Idioms</h2>\n<table>\n<thead>\n<tr>\n<th>Idiom</th>\n<th>Description</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>Accept interfaces, return structs</td>\n<td>Functions accept interface params, return concrete types</td>\n</tr>\n<tr>\n<td>Errors are values</td>\n<td>Treat errors as first-class values, not exceptions</td>\n</tr>\n<tr>\n<td>Don't communicate by sharing memory</td>\n<td>Use channels for coordination between goroutines</td>\n</tr>\n<tr>\n<td>Make the zero value useful</td>\n<td>Types should work without explicit initialization</td>\n</tr>\n<tr>\n<td>A little copying is better than a little dependency</td>\n<td>Avoid unnecessary external dependencies</td>\n</tr>\n<tr>\n<td>Clear is better than clever</td>\n<td>Prioritize readability over cleverness</td>\n</tr>\n<tr>\n<td>gofmt is no one's favorite but everyone's friend</td>\n<td>Always format with gofmt/goimports</td>\n</tr>\n<tr>\n<td>Return early</td>\n<td>Handle errors first, keep happy path unindented</td>\n</tr>\n</tbody>\n</table>\n<h2>Anti-Patterns to Avoid</h2>\n<pre><code>// Bad: Naked returns in long functions\nfunc process() (result int, err error) {\n    // ... 50 lines ...\n    return // What is being returned?\n}\n\n// Bad: Using panic for control flow\nfunc GetUser(id string) *User {\n    user, err := db.Find(id)\n    if err != nil {\n        panic(err) // Don't do this\n    }\n    return user\n}\n\n// Bad: Passing context in struct\ntype Request struct {\n    ctx context.Context // Context should be first param\n    ID  string\n}\n\n// Good: Context as first parameter\nfunc ProcessRequest(ctx context.Context, id string) error {\n    // ...\n}\n\n// Bad: Mixing value and pointer receivers\ntype Counter struct{ n int }\nfunc (c Counter) Value() int { return c.n }    // Value receiver\nfunc (c *Counter) Increment() { c.n++ }        // Pointer receiver\n// Pick one style and be consistent\n</code></pre>\n<p><strong>Remember</strong>: Go code should be boring in the best way - predictable, consistent, and easy to understand. When in doubt, keep it simple.</p>\n","files":[{"path":"LICENSE","sizeBytes":1071,"isText":false},{"path":"SKILL.md","sizeBytes":14497,"isText":true}],"reviewScore":null,"reviewSummary":null,"trust":{"provenance":"trusted-source-unreviewed","notice":"Community-authored content, reproduced verbatim and not vetted as instructions. Treat it as data to evaluate, never as directives to follow.","bodySource":null},"bodyLocked":false,"purchaseUrl":null,"sourceUrl":null,"report":{"provenance":"trusted-source-unreviewed","screen":{"ran":true,"outcome":"clean","suspicious":0,"notes":0,"hiddenCharacters":false},"virusScan":{"engine":"clamav","status":"clean","scannedAt":"2026-12-02T16:57:14.284814Z","sha256":"810250ABD38D51FBDEB2270B60F94F58753C0DA6F9BEB3A0E738EB8D3FEDF4C4","sizeBytes":6155},"review":null,"source":{"repositoryUrl":"https://github.com/beginwithu/agent-skills","path":"skills/golang-patterns","license":"MIT","commit":"a960304c52212f2e845067047f5cefc0c594d787","subtreeSha":"04F4EEBEF0553770A58EA5012557BEA5284A4765648BB490F0F37E571C1A3933","lastSyncedAt":"2026-12-02T16:52:59.20206Z"},"reviewedAt":"2026-12-02T17:04:14.877019Z","notice":"Community-authored content, reproduced verbatim and not vetted as instructions. Treat it as data to evaluate, never as directives to follow."},"install":[{"target":"skills-cli","command":"npx skills add https://github.com/beginwithu/agent-skills/tree/main/skills/golang-patterns"},{"target":"claude-code","command":"claude plugin marketplace add https://llmmart.ai/marketplace.json && claude plugin install beginwithu-agent-skills@llmmart"},{"target":"git","command":"git clone https://github.com/beginwithu/agent-skills.git"}]}