Communitygithub.com

golang-patterns

Padrões idiomáticos, melhores práticas e convenções Go para construir aplicações robustas, eficientes e de fácil manutenção. Use ao escrever ou revisar código Go e quando houver dúvidas sobre estrutura idiomática ou convenções.

O que é golang-patterns?

Este skill fornece um guia abrangente de padrões e práticas recomendadas para desenvolvimento em Go, cobrindo desde princípios fundamentais — como simplicidade, zero value útil e 'aceitar interfaces, retornar structs' — até padrões avançados de concorrência, tratamento de erros e design de pacotes. Ele é ativado automaticamente quando você escreve, revisa ou refatora código Go, ajudando a garantir que o código siga as convenções idiomáticas da linguagem. O documento inclui exemplos práticos de código, explicações detalhadas e anti-padrões para evitar, suportando plataformas como Claude Code, Cursor e Codex. Ao aplicar esses padrões, os desenvolvedores produzem código mais limpo, com melhor desempenho e mais fácil de manter, seguindo o espírito de 'clear is better than clever'.

Funciona com~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/affaan-m/everything-claude-code/tree/main/skills/golang-patterns

Perguntar na sua IA favorita

Abre um novo chat com esta habilidade de agente já pré-carregada.

Documentação

Padrões de Desenvolvimento Go

Padrões idiomáticos e melhores práticas Go para construir aplicações robustas, eficientes e de fácil manutenção.

Quando Ativar

  • Escrevendo novo código Go
  • Revisando código Go
  • Refatorando código Go existente
  • Projetando pacotes/módulos Go

Princípios Fundamentais

1. Simplicidade e Clareza

Go favorece simplicidade em vez de esperteza. O código deve ser óbvio e fácil de ler.

// Bom: Claro e direto
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
}

// Ruim: Excessivamente inteligente
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. Torne o Valor Zero Útil

Projete tipos para que seu valor zero seja imediatamente utilizável sem inicialização.

// Bom: Valor zero é útil
type Counter struct {
    mu    sync.Mutex
    count int // valor zero é 0, pronto para usar
}

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

// Bom: bytes.Buffer funciona com valor zero
var buf bytes.Buffer
buf.WriteString("hello")

// Ruim: Requer inicialização
type BadCounter struct {
    counts map[string]int // map nil vai causar pânico
}

3. Aceite Interfaces, Retorne Structs

Funções devem aceitar parâmetros de interface e retornar tipos concretos.

// Bom: Aceita interface, retorna tipo concreto
func ProcessData(r io.Reader) (*Result, error) {
    data, err := io.ReadAll(r)
    if err != nil {
        return nil, err
    }
    return &Result{Data: data}, nil
}

// Ruim: Retorna interface (esconde detalhes de implementação desnecessariamente)
func ProcessData(r io.Reader) (io.Reader, error) {
    // ...
}

Padrões de Tratamento de Erros

Empacotamento de Erros com Contexto

// Bom: Empacota erros com contexto
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
}

Tipos de Erro Personalizados

// Define erros específicos do domínio
type ValidationError struct {
    Field   string
    Message string
}

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

// Erros sentinela para casos comuns
var (
    ErrNotFound     = errors.New("resource not found")
    ErrUnauthorized = errors.New("unauthorized")
    ErrInvalidInput = errors.New("invalid input")
)

Verificação de Erros com errors.Is e errors.As

func HandleError(err error) {
    // Verifica erro específico
    if errors.Is(err, sql.ErrNoRows) {
        log.Println("Nenhum registro encontrado")
        return
    }

    // Verifica tipo de erro
    var validationErr *ValidationError
    if errors.As(err, &validationErr) {
        log.Printf("Erro de validação no campo %s: %s",
            validationErr.Field, validationErr.Message)
        return
    }

    // Erro desconhecido
    log.Printf("Erro inesperado: %v", err)
}

Nunca Ignore Erros

// Ruim: Ignorando erro com identificador vazio
result, _ := doSomething()

// Bom: Trata ou documenta explicitamente por que é seguro ignorar
result, err := doSomething()
if err != nil {
    return err
}

// Aceitável: Quando o erro realmente não importa (raro)
_ = writer.Close() // Limpeza de melhor esforço, erro registrado em outro lugar

Padrões de Concorrência

Pool de Workers

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 para Cancelamento e Timeouts

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)
}

Desligamento Gracioso

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

    <-quit
    log.Println("Desligando servidor...")

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

    if err := server.Shutdown(ctx); err != nil {
        log.Fatalf("Servidor forçado a desligar: %v", err)
    }

    log.Println("Servidor encerrado")
}

errgroup para Goroutines Coordenadas

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 // Captura variáveis do loop
        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
}

Evitando Vazamento de Goroutines

// Ruim: Vazamento de goroutine se o contexto for cancelado
func leakyFetch(ctx context.Context, url string) <-chan []byte {
    ch := make(chan []byte)
    go func() {
        data, _ := fetch(url)
        ch <- data // Bloqueia para sempre se não houver receptor
    }()
    return ch
}

// Bom: Trata corretamente o cancelamento
func safeFetch(ctx context.Context, url string) <-chan []byte {
    ch := make(chan []byte, 1) // Canal com buffer
    go func() {
        data, err := fetch(url)
        if err != nil {
            return
        }
        select {
        case ch <- data:
        case <-ctx.Done():
        }
    }()
    return ch
}

Design de Interfaces

Interfaces Pequenas e Focadas

// Bom: Interfaces de método único
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
}

// Componha interfaces conforme necessário
type ReadWriteCloser interface {
    Reader
    Writer
    Closer
}

Defina Interfaces Onde Elas São Usadas

// No pacote consumidor, não no provedor
package service

// UserStore define o que este serviço precisa
type UserStore interface {
    GetUser(id string) (*User, error)
    SaveUser(user *User) error
}

type Service struct {
    store UserStore
}

// A implementação concreta pode estar em outro pacote
// Ela não precisa saber sobre esta interface

Comportamento Opcional com Type Assertions

type Flusher interface {
    Flush() error
}

func WriteAndFlush(w io.Writer, data []byte) error {
    if _, err := w.Write(data); err != nil {
        return err
    }

    // Libera se suportado
    if f, ok := w.(Flusher); ok {
        return f.Flush()
    }
    return nil
}

Organização de Pacotes

Layout Padrão de Projeto

myproject/
├── cmd/
│   └── myapp/
│       └── main.go           # Ponto de entrada
├── internal/
│   ├── handler/              # Handlers HTTP
│   ├── service/              # Lógica de negócio
│   ├── repository/           # Acesso a dados
│   └── config/               # Configuração
├── pkg/
│   └── client/               # Cliente de API público
├── api/
│   └── v1/                   # Definições de API (proto, OpenAPI)
├── testdata/                 # Fixtures de teste
├── go.mod
├── go.sum
└── Makefile

Nomenclatura de Pacotes

// Bom: Curto, minúsculo, sem underscores
package http
package json
package user

// Ruim: Verboso, com maiúsculas/minúsculas misturadas ou redundante
package httpHandler
package json_parser
package userService // Sufixo 'Service' redundante

Evite Estado no Nível do Pacote

// Ruim: Estado global mutável
var db *sql.DB

func init() {
    db, _ = sql.Open("postgres", os.Getenv("DATABASE_URL"))
}

// Bom: Injeção de dependência
type Server struct {
    db *sql.DB
}

func NewServer(db *sql.DB) *Server {
    return &Server{db: db}
}

Design de Structs

Padrão de Opções Funcionais

type Server struct {
    addr    string
    timeout time.Duration
    logger  *log.Logger
}

type Option func(*Server)

func WithTimeout(d time.Duration) Option {
    return func(s *Server) {
        s.timeout = d
    }
}

func WithLogger(l *log.Logger) Option {
    return func(s *Server) {
        s.logger = l
    }
}

func NewServer(addr string, opts ...Option) *Server {
    s := &Server{
        addr:    addr,
        timeout: 30 * time.Second, // padrão
        logger:  log.Default(),    // padrão
    }
    for _, opt := range opts {
        opt(s)
    }
    return s
}

// Uso
server := NewServer(":8080",
    WithTimeout(60*time.Second),
    WithLogger(customLogger),
)

Embedding para Composição

type Logger struct {
    prefix string
}

func (l *Logger) Log(msg string) {
    fmt.Printf("[%s] %s\n", l.prefix, msg)
}

type Server struct {
    *Logger // Embedding - Server recebe método Log
    addr    string
}

func NewServer(addr string) *Server {
    return &Server{
        Logger: &Logger{prefix: "SERVER"},
        addr:   addr,
    }
}

// Uso
s := NewServer(":8080")
s.Log("Iniciando...") // Chama Logger.Log incorporado

Memória e Performance

Pré-alocar Slices Quando o Tamanho é Conhecido

// Ruim: Cresce o slice várias vezes
func processItems(items []Item) []Result {
    var results []Result
    for _, item := range items {
        results = append(results, process(item))
    }
    return results
}

// Bom: Alocação única
func processItems(items []Item) []Result {
    results := make([]Result, 0, len(items))
    for _, item := range items {
        results = append(results, process(item))
    }
    return results
}

Use sync.Pool para Alocações Frequentes

var bufferPool = sync.Pool{
    New: func() interface{} {
        return new(bytes.Buffer)
    },
}

func ProcessRequest(data []byte) []byte {
    buf := bufferPool.Get().(*bytes.Buffer)
    defer func() {
        buf.Reset()
        bufferPool.Put(buf)
    }()

    buf.Write(data)
    // Processa...
    return buf.Bytes()
}

Evite Concatenação de Strings em Loops

// Ruim: Cria muitas alocações de string
func join(parts []string) string {
    var result string
    for _, p := range parts {
        result += p + ","
    }
    return result
}

// Bom: Alocação única com strings.Builder
func join(parts []string) string {
    var sb strings.Builder
    for i, p := range parts {
        if i > 0 {
            sb.WriteString(",")
        }
        sb.WriteString(p)
    }
    return sb.String()
}

// Melhor: Use a biblioteca padrão
func join(parts []string) string {
    return strings.Join(parts, ",")
}

Integração com Ferramentas Go

Comandos Essenciais

# Compilar e executar
go build ./...
go run ./cmd/myapp

# Testes
go test ./...
go test -race ./...
go test -cover ./...

# Análise estática
go vet ./...
staticcheck ./...
golangci-lint run

# Gerenciamento de módulos
go mod tidy
go mod verify

# Formatação
gofmt -w .
goimports -w .

Configuração Recomendada de Linter (.golangci.yml)

linters:
  enable:
    - errcheck
    - gosimple
    - govet
    - ineffassign
    - staticcheck
    - unused
    - gofmt
    - goimports
    - misspell
    - unconvert
    - unparam

linters-settings:
  errcheck:
    check-type-assertions: true
  govet:
    enable:
      - shadow

issues:
  exclude-use-default: false

Referência Rápida: Expressões Idiomáticas Go

ExpressãoDescrição
Aceite interfaces, retorne structsFunções aceitam parâmetros de interface, retornam tipos concretos
Erros são valoresTrate erros como valores de primeira classe, não exceções
Não se comunique compartilhando memóriaUse canais para coordenação entre goroutines
Torne o valor zero útilTipos devem funcionar sem inicialização explícita
Um pouco de cópia é melhor que um pouco de dependênciaEvite dependências externas desnecessárias
Claro é melhor que inteligentePriorize legibilidade em vez de esperteza
gofmt não é o favorito de ninguém, mas é amigo de todosSempre formate com gofmt/goimports
Retorne cedoTrate erros primeiro, mantenha o caminho feliz não indentado

Anti-padrões a Evitar

// Ruim: Returns nus em funções longas
func process() (result int, err error) {
    // ... 50 linhas ...
    return // O que está sendo retornado?
}

// Ruim: Usar panic para controle de fluxo
func GetUser(id string) *User {
    user, err := db.Find(id)
    if err != nil {
        panic(err) // Não faça isso
    }
    return user
}

// Ruim: Passar context em struct
type Request struct {
    ctx context.Context // Context deve ser o primeiro parâmetro
    ID  string
}

// Bom: Context como primeiro parâmetro
func ProcessRequest(ctx context.Context, id string) error {
    // ...
}

// Ruim: Misturar receivers de valor e ponteiro
type Counter struct{ n int }
func (c Counter) Value() int { return c.n }    // Receiver de valor
func (c *Counter) Increment() { c.n++ }        // Receiver de ponteiro
// Escolha um estilo e seja consistente

Lembre-se: Código Go deve ser tedioso da melhor forma possível - previsível, consistente e fácil de entender. Em caso de dúvida, mantenha a simplicidade.

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

accessibility

Design, implement, and audit inclusive digital products using WCAG 2.2 Level AA. Use when building or auditing UI that must meet WCAG 2.2 Level AA, or when reviewing a change for keyboard, contrast, or screen-reader support.

affaan-m/claude-api

Anthropic Claude API patterns for Python and TypeScript. Covers Messages API, streaming, tool use, vision, extended thinking, batches, prompt caching, and Claude Agent SDK. Use when building applications with the Claude API or Anthropic SDKs.

affaan-m/everything-claude-code

End-to-end marketing campaign planning and execution. Covers audience research, positioning, campaign angle definition, landing page copy, email sequences, social posts, ad copy, short-form video scripts, and content calendars. Use as the orchestration layer for multi-channel product launches. Use when planning or executing a multi-channel product launch, or producing landing page, email, social, or ad copy.

affaan-m/everything-claude-code

Development conventions and patterns for everything-claude-code. JavaScript project with conventional commits.

affaan-m/everything-claude-code-conventions

Development conventions and patterns for everything-claude-code. JavaScript project with conventional commits.

affaan-m/frontend-design

Create distinctive, production-grade frontend interfaces with high design quality. Use when the user asks to build web components, pages, or applications and the visual direction matters as much as the code quality.

affaan-m/gget

gget CLI and Python workflow for quick genomic database queries, sequence lookup, BLAST-style searches, enrichment checks, and reproducible bioinformatics evidence logs.

affaan-m/literature-review

Systematic literature-review workflow for academic, biomedical, technical, and scientific topics, including search planning, source screening, synthesis, citation checks, and evidence logging.

affaan-m/motion-ui

Production-ready UI motion system for React/Next.js. Use when implementing animations, transitions, or motion patterns.

affaan-m/project-guidelines-example

Example project-specific skill template based on a real production application.

affaan-m/pubmed-database

Direct PubMed and NCBI E-utilities search workflows for biomedical literature, MeSH queries, PMID lookup, citation retrieval, and API-backed literature monitoring.

affaan-m/scholar-evaluation

Structured scholarly-work evaluation for papers, proposals, literature reviews, methods sections, evidence quality, citation support, and research-writing feedback.

affaan-m/uspto-database

USPTO patent and trademark data workflow for official record lookup, PatentSearch queries, TSDR checks, assignment data, and reproducible IP research logs.

agent-architecture-audit

Full-stack diagnostic for agent and LLM applications. Audits the 12-layer agent stack for wrapper regression, memory pollution, tool discipline failures, hidden repair loops, and rendering corruption. Produces severity-ranked findings with code-first fixes. Essential for developers building agent applications, autonomous loops, or any LLM-powered feature. Use when an agent or LLM feature misbehaves and the failing layer is unknown, or before shipping an agent stack.

agent-eval

Head-to-head comparison of coding agents (Claude Code, Aider, Codex, etc.) on custom tasks with pass rate, cost, time, and consistency metrics. Use when choosing between coding agents, or when a change to an agent setup needs measured pass rate, cost, and time rather than an impression.

agent-harness-construction

Design and optimize AI agent action spaces, tool definitions, and observation formatting for higher completion rates. Use when defining or revising an agent

agentic-engineering

Operate as an agentic engineer using eval-first execution, decomposition, and cost-aware model routing. Use when planning or executing engineering work that agents will carry out end to end.

agentic-os

Build persistent multi-agent operating systems on Claude Code. Covers kernel architecture, specialist agents, slash commands, file-based memory, scheduled automation, and state management without external databases. Use when building a persistent multi-agent system on Claude Code with its own memory, commands, and scheduling.

agent-introspection-debugging

Structured self-debugging workflow for AI agent failures using capture, diagnosis, contained recovery, and introspection reports. Use when an agent run fails and you need a reproducible diagnosis instead of a retry.

agent-payment-x402

Add x402 payment execution to AI agents with per-task budgets, spending controls, and non-custodial wallets. Supports Base through agentwallet-sdk and X Layer through OKX Payments / OKX Agent Payments Protocol. Use when an agent must pay for something itself and needs per-task budgets, spending controls, and a non-custodial wallet.

Habilidades Relacionadas