Communitygithub.com

patrones-go

Patrones idiomáticos de Go, mejores prácticas y convenciones para construir aplicaciones Go robustas, eficientes y mantenibles. Utilícelo al escribir o revisar código Go y cuando surjan dudas sobre estructura idiomática o convenciones.

¿Qué es patrones-go?

Este skill proporciona una guía completa de patrones idiomáticos y mejores prácticas para el desarrollo en Go, enfocándose en simplicidad, claridad y eficiencia. Es especialmente útil al escribir código nuevo, revisar código existente, refactorizar o diseñar paquetes y módulos en Go. El skill cubre principios fundamentales como hacer que el valor cero sea útil, aceptar interfaces y devolver structs, y manejo de errores con envoltura y tipos personalizados. También incluye patrones de concurrencia como worker pools, contextos para cancelación y timeouts, apagado graceful y uso de errgroup. Además, aborda diseño de interfaces pequeñas y enfocadas, organización de paquetes, patrones estructurales como opciones funcionales y embedding, optimización de memoria y rendimiento con preasignación de slices y sync.Pool, y herramientas esenciales de Go como go vet, golangci-lint y gofmt. El contenido está estructurado con ejemplos de código prácticos, tablas de referencia rápida y una sección de anti-patrones a evitar, lo que lo hace ideal para agentes de IA que asisten en tareas de codificación en Go en plataformas como Claude Code o Cursor.

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

Preguntar en tu IA favorita

Abre un nuevo chat con esta habilidad de agente ya precargada.

Documentación

Patrones de Desarrollo en Go

Patrones idiomáticos y mejores prácticas de Go para construir aplicaciones robustas, eficientes y mantenibles.

Cuándo Activar

  • Escribir código Go nuevo
  • Revisar código Go
  • Refactorizar código Go existente
  • Diseñar paquetes/módulos Go

Principios Fundamentales

1. Simplicidad y Claridad

Go favorece la simplicidad sobre la astucia. El código debe ser obvio y fácil de leer.

// Bueno: Claro y directo
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
}

// Malo: Demasiado ingenioso
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. Hacer que el Valor Cero Sea Útil

Diseña tipos para que su valor cero sea inmediatamente utilizable sin inicialización.

// Bueno: El valor cero es útil
type Counter struct {
    mu    sync.Mutex
    count int // el valor cero es 0, listo para usar
}

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

// Bueno: bytes.Buffer funciona con valor cero
var buf bytes.Buffer
buf.WriteString("hello")

// Malo: Requiere inicialización
type BadCounter struct {
    counts map[string]int // un mapa nil provocará pánico
}

3. Acepta Interfaces, Devuelve Structs

Las funciones deben aceptar parámetros de interfaz y devolver tipos concretos.

// Bueno: Acepta interfaz, devuelve 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
}

// Malo: Devuelve interfaz (oculta detalles de implementación innecesariamente)
func ProcessData(r io.Reader) (io.Reader, error) {
    // ...
}

Patrones de Manejo de Errores

Envoltura de Errores con Contexto

// Bueno: Envuelve errores con 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 Error Personalizados

// Define errores específicos del dominio
type ValidationError struct {
    Field   string
    Message string
}

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

// Errores centinela para casos comunes
var (
    ErrNotFound     = errors.New("resource not found")
    ErrUnauthorized = errors.New("unauthorized")
    ErrInvalidInput = errors.New("invalid input")
)

Verificación de Errores con errors.Is y errors.As

func HandleError(err error) {
    // Verifica si es un error específico
    if errors.Is(err, sql.ErrNoRows) {
        log.Println("No se encontraron registros")
        return
    }

    // Verifica si es de un tipo de error
    var validationErr *ValidationError
    if errors.As(err, &validationErr) {
        log.Printf("Error de validación en campo %s: %s",
            validationErr.Field, validationErr.Message)
        return
    }

    // Error desconocido
    log.Printf("Error inesperado: %v", err)
}

Nunca Ignorar Errores

// Malo: Ignorar error con identificador en blanco
result, _ := doSomething()

// Bueno: Maneja o documenta explícitamente por qué es seguro ignorar
result, err := doSomething()
if err != nil {
    return err
}

// Aceptable: Cuando el error realmente no importa (raro)
_ = writer.Close() // Limpieza de mejor esfuerzo, error registrado en otro lugar

Patrones de Concurrencia

Pool de Trabajadores

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

Contexto para Cancelación y 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)
}

Apagado Graceful

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

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

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

    if err := server.Shutdown(ctx); err != nil {
        log.Fatalf("Servidor forzado a apagar: %v", err)
    }

    log.Println("Servidor terminado")
}

errgroup para Gorutinas Coordinadas

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 // Capturar variables del bucle
        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
}

Evitar Fugas de Gorutinas

// Malo: Fuga de gorutina si el contexto se cancela
func leakyFetch(ctx context.Context, url string) <-chan []byte {
    ch := make(chan []byte)
    go func() {
        data, _ := fetch(url)
        ch <- data // Se bloquea para siempre si no hay receptor
    }()
    return ch
}

// Bueno: Maneja correctamente la cancelación
func safeFetch(ctx context.Context, url string) <-chan []byte {
    ch := make(chan []byte, 1) // Canal con buffer
    go func() {
        data, err := fetch(url)
        if err != nil {
            return
        }
        select {
        case ch <- data:
        case <-ctx.Done():
        }
    }()
    return ch
}

Diseño de Interfaces

Interfaces Pequeñas y Enfocadas

// Bueno: Interfaces de un solo método
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
}

// Compón interfaces según sea necesario
type ReadWriteCloser interface {
    Reader
    Writer
    Closer
}

Definir Interfaces Donde se Usan

// En el paquete consumidor, no en el proveedor
package service

// UserStore define lo que este servicio necesita
type UserStore interface {
    GetUser(id string) (*User, error)
    SaveUser(user *User) error
}

type Service struct {
    store UserStore
}

// La implementación concreta puede estar en otro paquete
// No necesita conocer esta interfaz

Comportamiento Opcional con Aserciones de Tipo

type Flusher interface {
    Flush() error
}

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

    // Flush si es compatible
    if f, ok := w.(Flusher); ok {
        return f.Flush()
    }
    return nil
}

Organización de Paquetes

Estructura de Proyecto Estándar

myproject/
├── cmd/
│   └── myapp/
│       └── main.go           # Punto de entrada
├── internal/
│   ├── handler/              # Manejadores HTTP
│   ├── service/              # Lógica de negocio
│   ├── repository/           # Acceso a datos
│   └── config/               # Configuración
├── pkg/
│   └── client/               # Cliente de API público
├── api/
│   └── v1/                   # Definiciones de API (proto, OpenAPI)
├── testdata/                 # Accesorios de prueba
├── go.mod
├── go.sum
└── Makefile

Nomenclatura de Paquetes

// Bueno: Corto, minúsculas, sin guiones bajos
package http
package json
package user

// Malo: Verboso, mayúsculas mezcladas o redundante
package httpHandler
package json_parser
package userService // Sufijo 'Service' redundante

Evitar Estado a Nivel de Paquete

// Malo: Estado mutable global
var db *sql.DB

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

// Bueno: Inyección de dependencias
type Server struct {
    db *sql.DB
}

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

Diseño de Structs

Patrón de Opciones Funcionales

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, // valor por defecto
        logger:  log.Default(),    // valor por defecto
    }
    for _, opt := range opts {
        opt(s)
    }
    return s
}

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

Embedding para Composición

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 obtiene el 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...") // Llama a Logger.Log embebido

Memoria y Rendimiento

Preasignar Slices Cuando se Conoce el Tamaño

// Malo: Hace crecer el slice múltiples veces
func processItems(items []Item) []Result {
    var results []Result
    for _, item := range items {
        results = append(results, process(item))
    }
    return results
}

// Bueno: Una sola asignación
func processItems(items []Item) []Result {
    results := make([]Result, 0, len(items))
    for _, item := range items {
        results = append(results, process(item))
    }
    return results
}

Usar sync.Pool para Asignaciones Frecuentes

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)
    // Procesar...
    return buf.Bytes()
}

Evitar la Concatenación de Cadenas en Bucles

// Malo: Crea muchas asignaciones de cadena
func join(parts []string) string {
    var result string
    for _, p := range parts {
        result += p + ","
    }
    return result
}

// Bueno: Una sola asignación con 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()
}

// Mejor: Usar la biblioteca estándar
func join(parts []string) string {
    return strings.Join(parts, ",")
}

Integración con Herramientas de Go

Comandos Esenciales

# Construir y ejecutar
go build ./...
go run ./cmd/myapp

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

# Análisis estático
go vet ./...
staticcheck ./...
golangci-lint run

# Gestión de módulos
go mod tidy
go mod verify

# Formateo
gofmt -w .
goimports -w .

Configuración 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

Referencia Rápida: Modismos de Go

ModismoDescripción
Acepta interfaces, devuelve structsLas funciones aceptan parámetros de interfaz, devuelven tipos concretos
Los errores son valoresTrata los errores como valores de primera clase, no como excepciones
No te comuniques compartiendo memoriaUsa canales para la coordinación entre gorutinas
Haz que el valor cero sea útilLos tipos deben funcionar sin inicialización explícita
Un poco de copia es mejor que un poco de dependenciaEvita dependencias externas innecesarias
Claro es mejor que ingeniosoPrioriza la legibilidad sobre la astucia
gofmt no es el favorito de nadie pero es amigo de todosSiempre formatea con gofmt/goimports
Retorna tempranoManeja los errores primero, mantén la ruta feliz sin sangría

Anti-patrones a Evitar

// Malo: Retornos desnudos en funciones largas
func process() (result int, err error) {
    // ... 50 líneas ...
    return // ¿Qué se está devolviendo?
}

// Malo: Usar panic para el flujo de control
func GetUser(id string) *User {
    user, err := db.Find(id)
    if err != nil {
        panic(err) // No hagas esto
    }
    return user
}

// Malo: Pasar contexto en un struct
type Request struct {
    ctx context.Context // El contexto debe ser el primer parámetro
    ID  string
}

// Bueno: Contexto como primer parámetro
func ProcessRequest(ctx context.Context, id string) error {
    // ...
}

// Malo: Mezclar receptores de valor y puntero
type Counter struct{ n int }
func (c Counter) Value() int { return c.n }    // Receptor de valor
func (c *Counter) Increment() { c.n++ }        // Receptor de puntero
// Elige un estilo y sé consistente

Recuerda: El código Go debe ser aburrido de la mejor manera: predecible, consistente y fácil de entender. En caso de duda, mantenlo simple.

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.

Skills relacionados