Logo vun Golang Patterns

Golang Patterns

Communautéit
j4flmao
golang-patterns

Use this skill when the user says 'Go goroutine', 'Go concurrency', 'Go channel', 'Go error handling', 'Go HTTP', 'Go middleware', 'Go context', 'Go worker pool', 'Go mutex', 'Go select', or when implementing Go-specific patterns. This skill enforces: goroutine lifecycle (every goroutine has a stop condition), errgroup for parallel work, error wrapping, HTTP handler DI via struct/closure, and graceful shutdown. Requires Go (go.mod). Do NOT use for: Go project structure, interface design, or non-Go patterns.

Iwwersiicht

Editeurj4flmao
Repositoryagent-skills
Skill-Nummgolang-patterns
Stären
41
Forks
6
Matgeliwwert Fichieren
5
LizenzMIT
Linken
  • Instruktiounen am Markdown-Format

    Eng SKILL.md-Datei, déi de Modell bei Bedarf luet, soudatt nëmmen Token ufalen, wann eng Ufro tatsächlech dozou passt.

  • Funktionéiert mat all LLM

    KI-Skills si reng Markdown, keen ubidderspezifesche Code. Dofir funktionéiert dëse Skill mat GPT, Claude, Gemini, Grok oder engem lokale Modell.

  • 5 matgeliwwert Dateien

    Skripten, Virlagen a Referenzen, déi de Modell beim Schaffe liese kann. D'Dateie kënnen nëmme gelies ginn a ginn ni ausgeféiert.

  • Open Source

    Vum j4flmao op GitHub verëffentlecht. Liest de Quelltext, ier Dir de Skill installéiert.

Installatioun

Installéiert de KI-Skill Golang Patterns an TypingMind, fir e mat all LLM ze benotzen, oder füügt en an en anere KI-Agent an, deen SKILL.md liest.

1

An TypingMind installéieren

TypingMind installéiert e Skill direkt aus sengem GitHub-Dossier — dobäi gëtt SKILL.md gelies, d'Ressourcedateie gi gebëndelt an d'Resultat gëtt lokal gespäichert.

  1. Maacht d'App op a gitt op Plugins → Skills.
  2. Wielt „Vun GitHub installéieren“.
  3. Pecht d'URL vum Skill-Dossier hei drënner an a bestätegt.
    https://github.com/j4flmao/agent-skills/tree/main/skills/backend/go/patterns
  4. Aktivéiert de Skill an all Chat, an deem Dir e benotze wëllt.
Plugins → Skills → Skill afügen → Vu GitHub-URL, pecht dann d'URL vum Dossier an a klickt op Weider.
2

An engem anere KI-Agent installéieren

All KI-Agent, deen d'Format Agent Skills liest, kann dëse Skill benotzen — kopéiert den Dossier an de Skill-Verzeechnes vun deem KI-Agent.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/j4flmao/agent-skills.git /tmp/agent-skills
mkdir -p .claude/skills
cp -r /tmp/agent-skills/skills/backend/go/patterns .claude/skills/golang-patterns
Start Claude Code nom Kopéieren nei, fir datt den neie Skill erkannt gëtt.

An TypingMind benotzen

Aktivéiert Golang Patterns an engem Chat vun TypingMind, an de Modell iwwerhëlt de Rescht. Den Numm an d'Beschreiwung stinn am System-Prompt. Soubal eng Ufro dozou passt, luet de Modell déi komplett Instruktioune selwer — Dir musst de Skill ni manuell opruffen, an et fale keng Token un, bis en tatsächlech benotzt gëtt.

De Modell luet Golang Patterns automatesch, soubal eng Ufro dozou passt.

Funktionéiert mat all KI-Modell

KI-Skills si reng Markdown-Instruktiounen amplaz vun ubidderspezifeschem Code. Dofir ass Golang Patterns net un de Modell gebonnen, fir deen de Skill geschriwwe gouf. Installéiert en eemol an TypingMind a benotzt e mat GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama oder engem lokale Modell, deen Dir selwer bedreift — alles mat Ären eegenen API-Keys.

  • Gëtt nëmme gelueden, wann et néideg ass

    De System-Prompt enthält nëmmen den Numm an d'Beschreiwung. D'Instruktioune gi bei der éischter passender Ufro gelueden, soudatt en onbenotzte Skill näischt kascht.

  • De Modell am lafende Chat wiesselen

    Well de Skill aus Instruktiounen amplaz vu Code besteet, funktionéiert en och no engem Modellwiessel — den nächste Modell liest déi selwecht SKILL.md-Datei.

Skill-Instruktiounen

Dëst ass den Inhalt vu SKILL.md, deen de Modell luet. Liest e virun der Installatioun — e Skill besteet aus Instruktiounen, déi Äre Modell befollegt.

Golang Patterns

Purpose

Implement Go concurrency, error handling, and HTTP server patterns correctly. Every goroutine has a stop condition. Every error is wrapped. Every server shuts down gracefully.

Agent Protocol

Trigger

Exact user phrases: "Go goroutine", "Go concurrency", "Go channel", "Go error handling", "Go HTTP", "Go middleware", "Go context", "Go worker pool", "Go mutex", "Go select", "Go graceful shutdown".

Input Context

Before activating, verify:

  • The pattern being implemented is known (worker pool, graceful shutdown, fan-out, etc.).
  • go.mod exists.

Output Artifact

No file output. Produces code examples as text.

Response Format

Pattern: {name}
Problem: {what this solves}
Code:
{implementation}

No preamble. No postamble. No explanations. No filler/hedging/transitions. Compress output — why use many token when few do trick.

Completion Criteria

  • Every goroutine has a context-based stop condition.
  • errgroup used for parallel work with error propagation.
  • Errors wrapped with context using fmt.Errorf("...%w").
  • HTTP handlers receive dependencies via struct or closure.
  • Graceful shutdown implemented with signal.NotifyContext.
  • Channels have clear ownership (creator closes, receiver reads).
  • No time.Sleep() for synchronization.

Max Response Length

Per pattern: 20 lines of code + 2 lines explanation.

Architecture Decision Trees

Concurrency Pattern Selection

PatternUse CaseChannel TypeGoroutine Count
Worker PoolFixed-size task processingBufferedFixed (N workers)
Fan-OutDistribute work to parallel consumersUnbufferedDynamic
Fan-InMerge results from multiple sourcesBuffered merge1 merger + N producers
PipelineSequential processing stagesUnbuffered1 per stage
Pub/SubBroadcast to multiple consumersBuffered per sub1 per subscriber

Decision: Fixed rate-limited processing → Worker Pool. Parallel independent tasks → Fan-Out/Fan-In. Sequential transformations → Pipeline. Event broadcast → Pub/Sub.

Error Propagation Strategy

StrategyMechanismBest For
errgroupFirst error cancels groupParallel independent tasks
Result channelErrors sent alongside resultsFan-In patterns
Custom error aggregatorCollect all errorsBatch validation
panic/recoverFatal unexpected errorsLibrary boundaries only

Decision: Fail-fast parallel work → errgroup. Continue-on-error collection → Result channel.

Workflow

Step 1: Goroutine Lifecycle

Every goroutine must have a mechanism to stop. Never start a goroutine without a done/cancel signal.

go
ctx, cancel := context.WithCancel(context.Background())
defer cancel()

go func() {
  for {
    select {
    case <-ctx.Done():
      return
    case job := <-jobChan:
      process(job)
    }
  }
}()

Step 2: errgroup for Parallel Work

go
g, ctx := errgroup.WithContext(context.Background())

for _, item := range items {
  item := item
  g.Go(func() error {
    result, err := processItem(ctx, item)
    if err != nil {
      return fmt.Errorf("process item %d: %w", item.ID, err)
    }
    results = append(results, result)
    return nil
  })
}

if err := g.Wait(); err != nil {
  return fmt.Errorf("batch processing failed: %w", err)
}

Step 3: Channel Ownership

  • The sender creates and closes the channel.
  • The receiver only reads from the channel.
  • Never close a channel on the receiver side.
  • Never write to a closed channel (panics).
go
func producer(ctx context.Context, items []Work) <-chan Work {
  out := make(chan Work)
  go func() {
    defer close(out)
    for _, item := range items {
      select {
      case <-ctx.Done():
        return
      case out <- item:
      }
    }
  }()
  return out
}

Step 4: HTTP Handler DI

go
// Struct-based DI
type UserHandler struct {
  createUser *application.CreateUserUseCase
  getUser    *application.GetUserUseCase
}

func NewUserHandler(createUser *application.CreateUserUseCase, getUser *application.GetUserUseCase) *UserHandler {
  return &UserHandler{createUser, getUser}
}

func (h *UserHandler) Create(w http.ResponseWriter, r *http.Request) {
  var dto application.CreateUserDTO
  if err := json.NewDecoder(r.Body).Decode(&dto); err != nil {
    writeError(w, http.StatusBadRequest, "INVALID_JSON", err.Error())
    return
  }
  user, err := h.createUser.Execute(r.Context(), dto)
  if err != nil {
    writeError(w, http.StatusInternalServerError, "INTERNAL", err.Error())
    return
  }
  writeJSON(w, http.StatusCreated, user)
}

// Closure-based DI (simpler)
func NewCreateHandler(uc *application.CreateUserUseCase) http.HandlerFunc {
  return func(w http.ResponseWriter, r *http.Request) {
    var dto application.CreateUserDTO
    if err := json.NewDecoder(r.Body).Decode(&dto); err != nil {
      writeError(w, http.StatusBadRequest, "INVALID_JSON", err.Error())
      return
    }
    user, err := uc.Execute(r.Context(), dto)
    if err != nil {
      writeError(w, http.StatusInternalServerError, "INTERNAL", err.Error())
      return
    }
    writeJSON(w, http.StatusCreated, user)
  }
}

Step 5: Graceful Shutdown

go
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()

server := &http.Server{Addr: ":8080", Handler: mux}
go func() {
  if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
    log.Fatalf("server error: %v", err)
  }
}()

<-ctx.Done()

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

if err := server.Shutdown(shutdownCtx); err != nil {
  log.Fatalf("shutdown error: %v", err)
}

Step 6: Worker Pool Pattern

go
type WorkerPool struct {
  jobs    chan Job
  results chan Result
  workers int
}

func NewWorkerPool(workers int) *WorkerPool {
  return &WorkerPool{
    jobs:    make(chan Job, 100),
    results: make(chan Result, 100),
    workers: workers,
  }
}

func (wp *WorkerPool) Start(ctx context.Context) {
  for i := 0; i < wp.workers; i++ {
    go func(id int) {
      for {
        select {
        case <-ctx.Done():
          return
        case job, ok := <-wp.jobs:
          if !ok {
            return
          }
          wp.results <- processJob(job)
        }
      }
    }(i)
  }
}

func (wp *WorkerPool) Submit(job Job) {
  wp.jobs <- job
}

func (wp *WorkerPool) Results() <-chan Result {
  return wp.results
}

func (wp *WorkerPool) Stop() {
  close(wp.jobs)
}

Step 7: Fan-Out/Fan-In Pattern

go
func fanOut(ctx context.Context, source <-chan Work, n int) []<-chan Work {
  workers := make([]<-chan Work, n)
  for i := 0; i < n; i++ {
    workers[i] = worker(ctx, source)
  }
  return workers
}

func worker(ctx context.Context, jobs <-chan Work) <-chan Work {
  results := make(chan Work)
  go func() {
    defer close(results)
    for j := range jobs {
      select {
      case <-ctx.Done():
        return
      case results <- process(j):
      }
    }
  }()
  return results
}

func fanIn(ctx context.Context, channels []<-chan Work) <-chan Work {
  out := make(chan Work)
  var wg sync.WaitGroup
  for _, ch := range channels {
    wg.Add(1)
    go func(c <-chan Work) {
      defer wg.Done()
      for v := range c {
        select {
        case <-ctx.Done():
          return
        case out <- v:
        }
      }
    }(ch)
  }
  go func() {
    wg.Wait()
    close(out)
  }()
  return out
}

Implementation Patterns

Pattern: Middleware Chain

go
type Middleware func(http.Handler) http.Handler

func Chain(h http.Handler, middleware ...Middleware) http.Handler {
  for i := len(middleware) - 1; i >= 0; i-- {
    h = middleware[i](h)
  }
  return h
}

// Usage
handler := Chain(
  userHandler,
  LoggerMiddleware,
  AuthMiddleware("admin"),
  RateLimitMiddleware(100),
)

Pattern: Context Values for Request Scope

go
type contextKey string

const UserIDKey contextKey = "user_id"

func WithUserID(ctx context.Context, id string) context.Context {
  return context.WithValue(ctx, UserIDKey, id)
}

func UserIDFromContext(ctx context.Context) (string, bool) {
  id, ok := ctx.Value(UserIDKey).(string)
  return id, ok
}

Production Considerations

Memory Management

  • sync.Pool for frequently allocated, short-lived objects (request contexts, buffers)
  • Pre-allocate slices with make([]T, 0, capacity) when capacity is known
  • Use runtime.GC() only after known allocations (unit tests), never in production
  • Profile with pprof — CPU, heap, goroutine, mutex profiles

Logging

go
// Structured logging with slog (Go 1.21+)
log := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
  Level: slog.LevelInfo,
}))
log.Info("request completed", "method", r.Method, "path", r.URL.Path, "status", 200, "duration", time.Since(start))

Anti-Patterns

Anti-PatternWhyFix
time.Sleep for synchronizationFlaky tests, wasted timeUse channels, WaitGroup, errgroup
context.Background() in library codeNever cancellablePass context from caller
Closing channel from receiverPanics senderCreator closes, receiver reads
panic in non-recoverable positionCrashes processReturn error instead
Global sync.WaitGroupUnclear ownershipScoped to function/call
select without default on single channelBlocks foreverUse for range or single <-ch

Security Considerations

  • Timeouts on all external calls: context.WithTimeout for database and HTTP requests
  • HTTP handler: set ReadHeaderTimeout, ReadTimeout, WriteTimeout, IdleTimeout on server
  • Validate and sanitize all handler inputs before passing to domain
  • Rate limit at HTTP middleware level, not per-goroutine

Testing Strategies

Testing Concurrency

go
func TestWorkerPool_ProcessesAllJobs(t *testing.T) {
  pool := NewWorkerPool(3)
  ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  defer cancel()
  pool.Start(ctx)

  for i := 0; i < 10; i++ {
    pool.Submit(Job{ID: i})
  }

  results := make([]Result, 0, 10)
  for i := 0; i < 10; i++ {
    select {
    case r := <-pool.Results():
      results = append(results, r)
    case <-ctx.Done():
      t.Fatal("timeout waiting for results")
    }
  }
  assert.Len(t, results, 10)
}

Race Detection

Always run with -race flag: go test -race ./.... Use sync.WaitGroup or errgroup for coordination. Never use atomic as a substitute for proper synchronization design.

Rules

  • Never start a goroutine without knowing how it will stop. context cancellation is the standard mechanism.
  • Use sync.WaitGroup or errgroup for synchronization. Never time.Sleep to wait for goroutines.
  • Only the sending side closes a channel (the owner that writes to it), never the receiver; closing twice or sending on a closed channel panics.
  • Always wrap errors with context: fmt.Errorf("load config: %w", err). "file not found" is useless without context.
  • context.Background() is created only at program entry points (main, tests, background workers). HTTP handlers use r.Context(); everything below receives ctx as the first parameter.
  • Never copy a sync.Mutex. Always pass as pointer.
  • Run go vet and go test -race in CI — vet catches misuse such as copied locks; the race detector finds data races on exercised code paths (it does not detect deadlocks).

References

  • references/concurrency-patterns.md — Go Concurrency Patterns
  • references/go-cli-patterns.md — Go CLI Application Patterns
  • references/go-microservices.md — Go Microservices Patterns
  • references/go-middleware.md — Go HTTP Middleware Patterns
  • references/http-server.md — Go HTTP Server

Handoff

No artifact produced. Next skill: backend-testing — test Go patterns. Carry forward: concurrency model, HTTP handler DI pattern, graceful shutdown.

Implementation Patterns

Pattern: Options Function

go
type ServerOption func(*Server)

func WithPort(port int) ServerOption {
    return func(s *Server) {
        s.port = port
    }
}

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

func NewServer(opts ...ServerOption) *Server {
    s := &Server{port: 8080, timeout: 30 * time.Second}
    for _, opt := range opts {
        opt(s)
    }
    return s
}

Pattern: Worker Pool

go
type Pool struct {
    jobs    chan Job
    results chan Result
    done    chan struct{}
}

func NewPool(numWorkers int) *Pool {
    p := &Pool{
        jobs:    make(chan Job, 100),
        results: make(chan Result, 100),
        done:    make(chan struct{}),
    }
    for i := 0; i < numWorkers; i++ {
        go p.worker()
    }
    return p
}

func (p *Pool) worker() {
    for job := range p.jobs {
        result := job.Execute()
        p.results <- result
    }
}

Production Considerations

  • Graceful shutdown: signal.NotifyContext for SIGINT/SIGTERM. Drain connections before exit.
  • Panic recovery: middleware recovers panics. Log stack trace. Return 500.
  • Resource limits: GOMAXPROCS set to CPU limit in container. ulimit -n for file descriptors.
  • Memory: Go runtime GC triggered by heap growth. Monitor go_memstats_alloc_bytes.
  • Goroutine leaks: ensure goroutines exit. Use context.Context for cancellation.
  • Profiling: pprof endpoints behind admin guard. CPU and heap profiles on demand.
  • Build: -ldflags="-s -w" for smaller binaries. -trimpath for reproducible builds.

Anti-Patterns

Anti-PatternWhy It HurtsFix
Global stateRace conditions. Untestable.Dependency injection. Pass dependencies explicitly.
Background goroutines without cleanupLeaked goroutines.errgroup.WithContext for lifecycle management.
context.Background() everywhereNo cancellation propagation.Derive context from request. Pass through call chain.
Interface pollutionMany single-method interfaces.Define interfaces where they're consumed, not produced.
recover() outside deferred funcPanic not caught.Always use defer recover() in goroutine entry points.
Deep package nestingImport cycles. Hard to navigate.Flat or shallow package layout. internal/ for private code.

Performance Optimization

  • json.Marshal / json.Unmarshal with json.Encoder/json.Decoder for streams.
  • sync.Pool for frequently allocated objects. Reduces GC pressure.
  • strings.Builder over bytes.Buffer for string concatenation.
  • Pre-allocate slices with make([]T, 0, capacity) when size is known.
  • Use map with struct keys over string keys for structured lookups.
  • io.Copy with io.Pipe for streaming transformations.
  • Escape analysis: prefer value receivers. Check with -gcflags="-m".
  • Since Go 1.25, GOMAXPROCS defaults to the container CPU limit on Linux; on older versions use go.uber.org/automaxprocs. runtime.GOMAXPROCS(0) only reads the current value.
  • Profile-guided optimization (Go 1.21+): place a CPU profile as default.pgo in the main package (picked up by the default -pgo=auto) or pass -pgo=path.

Security Considerations

  • Input validation: validator package for struct tags. Always validate at boundaries.
  • SQL injection: parameterized queries with database/sql. Never string concatenation.
  • XSS: html/template auto-escapes. Never use template.HTML with user input.
  • CSRF: token-based protection for web apps. Double-submit cookie pattern.
  • Secrets: environment variables or vault. Never hardcode. os.Getenv with defaults.
  • TLS: http.Server with TLSConfig. Minimum TLS 1.2. Strong cipher suites.
  • Rate limiting: token bucket per client IP. Sliding window for authenticated users.
  • CORS: rs/cors middleware. Allow specific origins only.
  • Authentication: JWT with golang-jwt/jwt. Short expiry. Refresh token rotation.

Matgeliwwert Fichieren

De Modell liest dës Dateie bei Bedarf, wärend de Skill gelueden ass. Si ginn als liesbar Dateie bereetgestallt a ginn ni ausgeféiert.

Heefeg gestallte Froen

Wat mécht de KI-Skill Golang Patterns?

Use this skill when the user says 'Go goroutine', 'Go concurrency', 'Go channel', 'Go error handling', 'Go HTTP', 'Go middleware', 'Go context', 'Go worker pool', 'Go mutex', 'Go select', or when implementing Go-specific patterns. This skill enforces: goroutine lifecycle (every goroutine has a stop condition), errgroup for parallel work, error wrapping, HTTP handler DI via struct/closure, and graceful shutdown. Requires Go (go.mod). Do NOT use for: Go project structure, interface design, or non-Go patterns.

Firwat Golang Patterns op TypingMind benotzen?

Well Dir en eemol installéiert a mat all Modell benotze kënnt. Golang Patterns besteet aus einfachem Markdown amplaz vun ubidderspezifeschem Code. Dee selwechte Skill funktionéiert also mat GPT-5, Claude, Gemini, Grok oder engem lokale Modell – an Dir kënnt de Modell matzen am Chat wiesselen, ouni datt de Skill ophält ze funktionéieren. TypingMind benotzt Är eegen API-Schlësselen, sou datt Dir d'Ubidder direkt bezuelt amplaz vun engem Abonnement pro Benotzerplaz. Är Skills a Chats bleiwen an Ärem eegene Späicher.

Wéi installéieren ech Golang Patterns an TypingMind?

Maacht an TypingMind Plugins → Skills → Vu GitHub installéieren op a setzt https://github.com/j4flmao/agent-skills/tree/main/skills/backend/go/patterns an. TypingMind liest d'Datei SKILL.md, bündelt déi zougehéiereg Dateien an installéiert dat Ganzt als Skill, deen Dir pro Chat aktivéiere kënnt.

Wéi eng KI-Modeller kënnen Golang Patterns benotzen?

All Modell, deen Dir an TypingMind verbënnt. KI-Skills sinn einfach Markdown-Instruktiounen an net ubidderspezifesche Code. Dofir kënne GPT, Claude, Gemini, Grok a lokal Modeller dëse Skill lueden, wann eng Ufro dozou passt.

Wéi vill KI-Modeller kann ech mat Golang Patterns benotzen?

Esou vill Dir wëllt. Soulaang e Modell Skills ënnerstëtzt, kënnt Dir Golang Patterns domat benotzen – GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama a méi – alles op TypingMind mat Ären eegenen API-Schlësselen.

Ass de KI-Skill Golang Patterns gratis?

Jo. De Skill gëtt vum j4flmao ënner der Lizenz MIT op GitHub publizéiert. Dir bezuelt nëmmen Ären eegene KI-Ubidder fir d'Token, déi Dir benotzt.

Wat si KI-Skills?

E KI-Skill ass e weiderverwendbaart Pak vun Instruktiounen, dat engem KI-Modell bäibréngt, wéi en eng bestëmmt Aufgab erfëllt. E follegt dem oppenen Agent Skills-Format: eng Datei SKILL.md mat engem Numm an enger Beschreiwung, plus all Scripten, Virlagen oder Referenzdateien, déi de Modell eventuell brauch. De Modell liest d'Instruktiounen eréischt, wann Är Ufro zum Skill passt. En installéierte Skill kascht also näischt, bis e benotzt gëtt.

Wéi ënnerscheede sech KI-Skills vu Plugins oder MCP-Serveren?

E Plugin oder MCP-Server gëtt engem Modell nei Tools, déi en opruffe kann – Code, deen iergendwou leeft an e Resultat zeréckgëtt. E KI-Skill gëtt dem Modell dogéint Wëssen an eng Virgoensweis: wéi en eng Aufgab ugeet, wéi eng Schrëtt en nokënnt a wéi eng gutt Ausgab ausgesäit. Skills bestinn aus einfachem Markdown, brauche kee Server, keen API-Schlëssel a keng Lafzäitëmfeld a funktionéiere mat all Modell.

All weisen

Elo Ären eegene KI-Workspace ariichten

Abonnéiert Iech op eisen Newsletter, fir iwwer nei Funktiounen an zukünfteg Gewënnspiller informéiert ze ginn 👇