Logotipo de Debug Go

Debug Go

Comunidad
yerdaulet-damir
debug-go

Systematic 5-step debugging flow for Go 1.22+ services. Load when a test fails, a goroutine leaks, a downstream provider hangs, errors lose context, or production logs are unhelpful. Forces layer isolation (handler vs service vs repo vs provider) and runs the 5 most common Go antipattern greps before any code change — prevents the "add a goroutine to fix a slow handler" cascade.

Descripción general

Editoryerdaulet-damir
Repositoriovibe-coding-rules
Nombre de la habilidaddebug-go
Estrellas
34
Forks
1
Archivos incluidos
Solo instrucciones
LicenciaMIT
Enlaces
  • Instrucciones en Markdown

    Un archivo SKILL.md que el modelo carga cuando lo necesita, de modo que solo consume tokens cuando una petición es realmente relevante.

  • Funciona con cualquier LLM

    Las habilidades de IA están en Markdown, no en código específico de un proveedor, por lo que funcionan con GPT, Claude, Gemini, Grok o un modelo local.

  • Todo en las instrucciones

    Todo lo que necesita el modelo está en las instrucciones: no hay archivos adicionales que sincronizar.

  • Código abierto

    Publicada por yerdaulet-damir en GitHub. Revisa el contenido original antes de instalarla.

Instalación

Instala la habilidad de IA Debug Go en TypingMind para usarla con cualquier LLM, o añádela a otro agente que lea SKILL.md.

1

Instalar en TypingMind

TypingMind instala una habilidad directamente desde su carpeta de GitHub: lee SKILL.md, empaqueta los archivos de recursos y guarda el resultado localmente.

  1. Abre la aplicación y ve a Plugins → Habilidades.
  2. Elige «Instalar desde GitHub».
  3. Pega la URL de la carpeta de la habilidad que se muestra a continuación y confirma.
    https://github.com/yerdaulet-damir/vibe-coding-rules/tree/main/.claude/skills/debug-go
  4. Activa la habilidad en cada chat en el que quieras tenerla disponible.
Plugins → Habilidades → Añadir habilidad → Desde URL de GitHub; después, pega la URL de la carpeta y pulsa Continuar.
2

Instalar en otro agente

Cualquier agente que lea el formato Agent Skills puede usar esta habilidad: copia la carpeta en el directorio de habilidades de ese agente.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/yerdaulet-damir/vibe-coding-rules.git /tmp/vibe-coding-rules
mkdir -p .claude/skills
cp -r /tmp/vibe-coding-rules/.claude/skills/debug-go .claude/skills/debug-go
Reinicia Claude Code después de copiarla para que detecte la nueva habilidad.

Úsala en TypingMind

Activa Debug Go en cualquier chat de TypingMind y el modelo se encargará del resto. Su nombre y descripción se incluyen en el prompt del sistema y, en cuanto una petición es relevante, el modelo carga las instrucciones completas por sí solo. No tienes que invocarla manualmente y no consume tokens hasta que se utiliza.

El modelo carga Debug Go automáticamente en cuanto una petición es relevante para esa habilidad.

Funciona con cualquier modelo de IA

Las habilidades de IA son instrucciones en Markdown, no código específico de un proveedor, por lo que Debug Go no está vinculada al modelo para el que se creó. Instálala una sola vez en TypingMind y úsala con GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama o un modelo local que ejecutes tú, todo con tus propias claves API.

  • Se carga solo cuando se necesita

    El prompt del sistema solo incluye el nombre y la descripción. Las instrucciones se cargan con la primera petición relevante, por lo que una habilidad que no se usa no supone ningún coste.

  • Cambia de modelo durante el chat

    Como la habilidad contiene instrucciones y no código, cambiar de modelo no impide que funcione: el nuevo modelo lee el mismo archivo SKILL.md.

Instrucciones de la habilidad

Este es el contenido de SKILL.md que carga el modelo. Léelo antes de instalar la habilidad: contiene instrucciones que tu modelo seguirá.

debug-go

Stop. Do not edit any file yet. Work through these 5 steps in order.


Step 1 — Locate the layer

Go bugs almost always live in one of these layers. Identify which one before touching code.

SymptomLikely layerFirst grep
500 in prod, no useful logHandler — error mappinggrep -n "errors.Is|errors.As" internal/server/handlers.go
Wrong amount / state after mutationService / repogrep -n "Hold|Confirm|Refund" internal/<domain>/service.go
Hangs under loadHTTP client / bulkheadgrep -rn "http.DefaultClient|MaxConnsPerHost" internal/
context deadline exceeded everywhereMissing ctx propagationgrep -rn "context.Background()|context.TODO()" internal/
Goroutine leak in pproferrgroup not used / unclosed channelsgrep -rn "go func\b" internal/
Test passes locally, race on CIShared mutable statego test ./... -race
Panic crashes serverMissing recover middlewaregrep -rn "recover()" internal/server/
Downstream API change broke usProvider parsergrep -rn "json.Unmarshal|json.NewDecoder" internal/providers/

Pick one layer. Do not touch any other layer in this debug pass.


Step 2 — Run the 5 most common Go antipattern greps

bash
# Antipattern 1: http.DefaultClient (no per-provider isolation)
grep -rn "http\.DefaultClient" internal/

# Antipattern 2: context.Background() / context.TODO() in non-main code
grep -rn "context\.Background()\|context\.TODO()" internal/ \
  --include="*.go" | grep -v "_test.go"

# Antipattern 3: panic in production code
grep -rn "panic(" internal/ --include="*.go" | grep -v "_test.go\|recover"

# Antipattern 4: fmt.Println / log.Printf instead of slog
grep -rn "fmt\.Println\|log\.Printf" internal/ --include="*.go" | grep -v "_test.go"

# Antipattern 5: errors not wrapped with %w
grep -rn "errors\.New(\"[^%]*: \"" internal/ --include="*.go"
# Hits with concatenation suggest a missed `%w` opportunity.
ResultRoot causePrinciple
http.DefaultClient usedBulkhead broken — one slow downstream blocks allF4
context.Background() in handler chainLost cancellation/deadline propagationF2
panic() in handler/serviceServer crashes on edge caseF3
fmt.Println/log.PrintfLogs without context, unsearchableF6
errors.New with concatenated contextLost error chain, errors.Is/As failsF3

Step 3 — Reproduce with go test -run and -race

For service/repo bugs — write a failing test first:

go
func TestService_RaceOnConcurrentCharge(t *testing.T) {
    t.Parallel()
    svc := newTestService(t, dec("10.00"))
    ctx := context.Background()

    // Two concurrent charges with the same idempotency key.
    // Should hold once, not twice.
    var wg sync.WaitGroup
    var ids [2]string
    for i := 0; i < 2; i++ {
        i := i
        wg.Add(1)
        go func() {
            defer wg.Done()
            id, _ := svc.Charge(ctx, "u-1", dec("4.00"), "idem-x")
            ids[i] = id
        }()
    }
    wg.Wait()
    if ids[0] != ids[1] {
        t.Fatalf("idempotency violated: %s vs %s", ids[0], ids[1])
    }
}

Run it:

bash
go test -run TestService_RaceOnConcurrentCharge -race -v ./internal/credits/

It must FAIL before the fix.

For HTTP client / provider bugs — use httptest.Server to simulate the failure:

go
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    w.WriteHeader(http.StatusTooManyRequests)
}))
defer srv.Close()

p := &FalAI{client: srv.Client(), baseURL: srv.URL, log: slog.Default()}
_, err := p.Generate(context.Background(), JobRequest{ModelID: "m", Prompt: "p"})
if !errors.Is(err, ErrRateLimited) {
    t.Fatalf("expected ErrRateLimited, got %v", err)
}

Step 4 — Fix in the correct layer

Minimum change. Do not refactor unrelated code.

LayerWhere to fix
Handler / error → HTTP codeinternal/server/handlers.go
Business logicinternal/<domain>/service.go
Persistence / concurrencyinternal/<domain>/repository.go
External API parsinginternal/providers/<name>.go (the ACL)
HTTP client configinternal/httpclient/client.go
Logging contextinternal/context/keys.go + middleware
Graceful shutdowninternal/server/run.go

Goroutine leaks specifically: add errgroup with a parent context.WithCancel. Every go func should be replaceable by g.Go(func() error { ... }). (Principle F8.)


Step 5 — Verify

bash
# Type / vet check
go vet ./...

# Race detector — catches concurrency bugs you can't see by reading
go test ./... -race

# All tests pass
go test ./...

# (If you have a linter)
golangci-lint run

Then re-run all 5 antipattern greps from Step 2. You must not have introduced any new violations while fixing.


Common error → root cause table

Error / SymptomWhere to lookLikely cause
runtime error: invalid memory addressnil pointerA struct field not initialized — check the constructor
concurrent map read and writeshared mutable mapAdd sync.Mutex or use sync.Map if read-heavy
context deadline exceeded cascading everywhereparent ctxProbably a fixed context.WithTimeout(ctx, 1s) upstream
dial tcp: i/o timeoutnetwork or DNSCheck provider client Timeout; check pod DNS
too many open filesFD exhaustionBulkhead violation (F4): a hung downstream eating the pool
Test hangs foreverUnbuffered channelProducer goroutine exited without sending; receiver waits forever
interface conversion: ... is not ...wrong concrete typeHandler accepts a too-wide interface; tighten with the smallest method set
Panic mid-request, server stays up but log is silentrecover swallowsMake sure the recover middleware logs rec and debug.Stack()
Server doesn't drain on SIGTERMsignal.Notify not wiredUse signal.NotifyContext (Go 1.16+) — Principle F7
Provider response field appears null after parseUnmarshal hit zero valueCheck JSON tag spelling; use *string if true-null matters

Verification

The skill was applied correctly when:

  • A reproducible test exists (Step 3) — failing before, passing after
  • Fix touches exactly one layer
  • All 5 antipattern greps still come up clean
  • go vet ./... && go test ./... -race exits 0
  • No new file exceeds 500 LOC; no new package named utils/helpers/common

Preguntas frecuentes

¿Qué hace la habilidad de IA Debug Go?

Systematic 5-step debugging flow for Go 1.22+ services. Load when a test fails, a goroutine leaks, a downstream provider hangs, errors lose context, or production logs are unhelpful. Forces layer isolation (handler vs service vs repo vs provider) and runs the 5 most common Go antipattern greps before any code change — prevents the "add a goroutine to fix a slow handler" cascade.

¿Por qué usar Debug Go en TypingMind?

Porque la instalas una vez y la usas con cualquier modelo. Debug Go está escrita en Markdown, no en código específico de un proveedor, por lo que la misma habilidad funciona con GPT-5, Claude, Gemini, Grok o un modelo local, y puedes cambiar de modelo en mitad del chat sin que deje de funcionar. TypingMind utiliza tus propias claves API, de modo que pagas directamente a los proveedores en lugar de pagar una suscripción por puesto, y tus habilidades y chats permanecen en tu propio almacenamiento.

¿Cómo instalo Debug Go en TypingMind?

Abre Plugins → Habilidades → Instalar desde GitHub en TypingMind y pega https://github.com/yerdaulet-damir/vibe-coding-rules/tree/main/.claude/skills/debug-go. TypingMind lee su archivo SKILL.md y la instala como una habilidad que puedes activar en cada chat.

¿Qué modelos de IA pueden usar Debug Go?

Cualquier modelo que conectes en TypingMind. Las habilidades de IA son instrucciones en Markdown, no código específico de un proveedor, por lo que GPT, Claude, Gemini, Grok y los modelos locales pueden cargar esta habilidad cuando una solicitud se corresponda con ella.

¿Con cuántos modelos de IA puedo usar Debug Go?

Con tantos como quieras. Siempre que un modelo admita habilidades, puedes usar Debug Go con él: GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama y muchos más, todos en TypingMind con tus propias claves API.

¿Es gratuita la habilidad de IA Debug Go?

Sí. yerdaulet-damir la ha publicado en GitHub bajo la licencia MIT. Solo pagas a tu proveedor de IA por los tokens que utilizas.

¿Qué son las habilidades de IA?

Una habilidad de IA es un conjunto de instrucciones reutilizables que enseña a un modelo de IA a realizar una tarea concreta. Sigue el formato abierto Agent Skills: un archivo SKILL.md con un nombre y una descripción, además de los scripts, plantillas o archivos de referencia que pueda necesitar el modelo. El modelo solo lee las instrucciones cuando tu solicitud se corresponde con la habilidad, por lo que una habilidad instalada no supone ningún coste hasta que se utiliza.

¿En qué se diferencian las habilidades de IA de los plugins o los servidores MCP?

Un plugin o un servidor MCP proporciona al modelo nuevas herramientas que puede invocar: código que se ejecuta en algún lugar y devuelve un resultado. En cambio, una habilidad de IA aporta conocimientos y procedimientos al modelo: cómo abordar una tarea, qué pasos seguir y qué se considera un buen resultado. Las habilidades son instrucciones en Markdown, por lo que no necesitan servidor, clave API ni entorno de ejecución, y funcionan con cualquier modelo.

Ver todos

Crea ya tu propio espacio de trabajo IA

Suscríbete a nuestro boletín para recibir avisos sobre nuevas funciones y próximos sorteos 👇