Communitygithub.com

samber/golang-safety

Defensives Go-Coding zur Vermeidung von Panics, stiller Datenkorruption und subtilen Laufzeitfehlern. Verwenden bei nil-Panics, Append-Aliasing, nebenläufigem Map-Zugriff, Fallstricken beim Float-Vergleich oder Fragen zum Zero-Value-Design. Auch verwenden beim Code-Review für nil-Sicherheit, Integer-Überlauf bei Konvertierung, Ressourcenlebenszyklusprobleme (defer in Schleifen) oder defensives Kopieren von Slices und Maps.

Was ist golang-safety?

Diese Fähigkeit ist ein umfassender Leitfaden für defensives Go-Coding und adressiert häufige, aber schwer zu findende Fehler in Go-Programmen. Sie ist nützlich für Entwickler, die Code schreiben oder reviewen, der anfällig für Panics, Datenkorruption und subtile Laufzeitfehler ist. Basierend auf der SKILL.md-Dokumentation behandelt die Fähigkeit Kernbereiche wie nil-Sicherheit (nil-Panics, nil Slices/Maps/Channels), Append-Aliasing, nebenläufigen Map-Zugriff, Fallstricke beim Float-Vergleich, Prüfung und fehlerhafte Verwendung des Zero-Value-Designs sowie defensive Kopiertechniken für Slices und Maps. Sie bietet bewährte Praktiken und Code-Vorlagen, um jede dieser Fallen zu vermeiden. Die Fähigkeit fungiert als mentales Checkliste und Nachschlagewerk und ist auf jeder Plattform anwendbar, die die Entwicklung mit Go und dem AI-Assistenten unterstützt.

Funktioniert mit~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/samber/cc-skills-golang/tree/main/skills/golang-safety

In Ihrer bevorzugten KI fragen

Öffnet einen neuen Chat, in dem dieser Agent-Skill bereits geladen ist.

Dokumentation

Was macht golang-safety?

Defensives Go-Coding zur Vermeidung von Panics, stiller Datenkorruption und subtilen Laufzeitfehlern. Verwenden bei nil-Panics, Append-Aliasing, nebenläufigem Map-Zugriff, Fallstricken beim Float-Vergleich oder Fragen zum Zero-Value-Design. Auch verwenden beim Code-Review für nil-Sicherheit, Integer-Überlauf bei Konvertierung, Ressourcenlebenszyklusprobleme (defer in Schleifen) oder defensives Kopieren von Slices und Maps.

Einführung

Go ist eine schlanke und dennoch ausdrucksstarke Sprache. Ähnlich wie C bietet sie eine geringe Abstraktion, erfordert aber ein starkes Bewusstsein für die Speicherverwaltung. Im Gegensatz zu Sprachen mit Garbage Collectors kann Go den Programmierer stillen Datenkorruption und subtilen Speicherlecks aussetzen.

Diese Fähigkeit bietet einen strukturierten Ansatz, um diese häufigen Fallstricke zu vermeiden. Sie ist für jeden Go-Entwickler gedacht, der beim Schreiben oder Überprüfen von Go-Code defensiv vorgehen möchte.

Häufige Fallstricke und Gegenmaßnahmen

1. nil-Panics und nil-Sicherheit

Go-Panics (z.B. nil pointer dereference) sind Laufzeitfehler, die eine sofortige Korrektur erfordern. Sie treten häufig auf, wenn man den nil-Zustand nicht prüft.

Problem:

var m map[string]int
m["key"] = 1  // panic: Zuweisung zu einem nil-map-Eintrag

Empfohlene Vorgehensweise:

  • Prüfen Sie immer auf nil, bevor Sie Methoden auf Empfängern aufrufen.
  • Initialisieren Sie Maps und Slices mit make(), es sei denn, Sie erwarten ausdrücklich nil.
  • Verwenden Sie das Komma-Ok-Idiom für den Zugriff auf Typ-Assertionen und Maps.
func (s *Service) DoSomething() error {
    if s == nil {
        return errors.New("Service ist nil")
    }
    // ... sicherer Code
}

2. Append-Aliasing

Aufgrund der Art und Weise, wie Go-Slices funktionieren, kann append() unbeabsichtigt Quelldaten überschreiben, wenn die Kapazität ausreicht und keine neue Zuweisung erfolgt.

Problem:

a := []int{1, 2, 3}
b := a[:2]
b = append(b, 99)  // Überschreibt a[2]!
fmt.Println(a)  // [1 2 99]

Empfohlene Vorgehensweise:

// Erstellen Sie ein neues Slice, um Aliasing zu vermeiden
a := []int{1, 2, 3}
b := make([]int, 2)
copy(b, a[:2])
b = append(b, 99)
fmt.Println(a)  // [1 2 3] - sicher

3. Nebenläufiger Map-Zugriff

Maps in Go sind nicht thread-sicher. Gleichzeitiges Lesen und Schreiben führt zu einem Laufzeit-Panic concurrent map writes.

Problem:

m := make(map[string]int)
go func() { m["a"] = 1 }()
go func() { m["b"] = 2 }()  // Panic: concurrent map writes

Empfohlene Vorgehensweise:

Verwenden Sie sync.Mutex oder sync.RWMutex:

import "sync"

type SafeMap struct {
    mu sync.RWMutex
    m  map[string]int
}

func (s *SafeMap) Get(key string) int {
    s.mu.RLock()
    defer s.mu.RUnlock()
    return s.m[key]
}

func (s *SafeMap) Set(key string, val int) {
    s.mu.Lock()
    defer s.mu.Unlock()
    s.m[key] = val
}

Oder ziehen Sie Go 1.21+ sync.Map für bestimmte Anwendungsfälle in Betracht.

4. Falle beim Float-Vergleich

Gleitkommazahlen sollten niemals mit == verglichen werden. Akkumulierte Rundungsfehler führen zu unerwarteten Ergebnissen.

Problem:

if 0.1+0.2 == 0.3 {  // Dies ist false!
    fmt.Println("gleich")
}

Empfohlene Vorgehensweise:

import "math"

const epsilon = 1e-9

if math.Abs((0.1+0.2)-0.3) < epsilon {
    fmt.Println("innerhalb der Toleranz")
}

5. Zero-Value-Design-Falle

Jeder Typ in Go hat einen Zero-Value. Der nil-Empfänger ist ein spezieller Fall, der Panics verursachen kann.

Problem:

type Config struct {
    Timeout time.Duration
    Host    string
    Port    int
}

var cfg Config  // Zero-Werte: Timeout=0, Host="", Port=0
// Host und Port sind gültig? Vielleicht möchten wir, dass sie required sind.

Empfohlene Vorgehensweise:

Erwägen Sie entweder eine explizite Struktur-Validierung oder die Verwendung von Zeigertypen, um zwischen "nicht gesetzt" und "Zero" zu unterscheiden:

type Config struct {
    Timeout *time.Duration  // nil bedeutet 'nicht gesetzt'
    Host    *string         // nil bedeutet 'nicht gesetzt'
    Port    *int            // nil bedeutet 'nicht gesetzt'
}

func (c Config) Validate() error {
    if c.Host == nil {
        return errors.New("Host ist erforderlich")
    }
    return nil
}

6. Defensives Kopieren von Slices und Maps

Das direkte Zuweisen eines Slices/einer Map wird diese zwischen Empfänger und Aufrufer teilen, was zu unerwarteten Mutationen führt.

Problem:

type MyStruct struct {
    Items []string
}

func NewMyStruct(items []string) *MyStruct {
    return &MyStruct{Items: items}  // Teilt dasselbe zugrunde liegende Array
}

Empfohlene Vorgehensweise:

func NewMyStruct(items []string) *MyStruct {
    newItems := make([]string, len(items))
    copy(newItems, items)
    return &MyStruct{Items: newItems}
}

Ähnlich für Maps:

m := map[string]int{"a": 1}
m2 := make(map[string]int)
for k, v := range m {
    m2[k] = v
}

Ressourcen / Weiterführende Literatur

Lizenz

Apache 2.0

Individual skills in this repo

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

samber/golang-benchmark

Golang benchmarking, profiling, and performance measurement. Use when writing, running, or comparing Go benchmarks, profiling hot paths with pprof, interpreting CPU/memory/trace profiles, analyzing results with benchstat, setting up CI benchmark regression detection, or investigating production performance with Prometheus runtime metrics. Also use when the developer needs deep analysis on a specific performance indicator - this skill provides the measurement methodology, while `samber/cc-skills-golang@golang-performance` provides the optimization patterns.

samber/golang-cli

Golang CLI application development. Use when building, modifying, or reviewing a Go CLI tool — especially for command structure, flag handling, configuration layering, version embedding, exit codes, I/O patterns, signal handling, shell completion, argument validation, and CLI unit testing. Also triggers when code uses cobra, viper, or urfave/cli. For cobra-specific APIs → See `samber/cc-skills-golang@golang-spf13-cobra` skill; for viper configuration layering → See `samber/cc-skills-golang@golang-spf13-viper` skill.

samber/golang-code-style

Golang code style conventions — line length and breaking, variable declarations, control flow clarity, when comments help vs hurt. Use when writing or reviewing Go code, asking about style or clarity, or establishing project coding standards. Not for naming conventions (→ See `samber/cc-skills-golang@golang-naming` skill), linter configuration (→ See `samber/cc-skills-golang@golang-lint` skill), or doc comments (→ See `samber/cc-skills-golang@golang-documentation` skill).

samber/golang-concurrency

Golang concurrency patterns. Use when writing or reviewing concurrent Go code involving goroutines, channels, select, locks, sync primitives, errgroup, singleflight, worker pools, or fan-out/fan-in pipelines. Also triggers when you detect goroutine leaks, race conditions, channel ownership issues, or need to choose between channels and mutexes.

samber/golang-context

Idiomatic context.Context usage in Golang — propagation through API boundaries, cancellation, timeouts and deadlines, request-scoped values, context.WithoutCancel for background work outliving requests. Apply when designing context propagation across layers, debugging leaked or unexpired contexts, choosing between context.Background/TODO/WithoutCancel, or storing values in context. Not for code that merely accepts ctx as first parameter.

samber/golang-continuous-integration

CI/CD pipeline configuration using GitHub Actions for Golang projects — testing, linting, SAST, security scanning, code coverage, Dependabot, Renovate, GoReleaser, code review automation, and release pipelines. Use when setting up or improving Go project CI, configuring GitHub Actions workflows, adding linters or security scanners, automating dependency updates, or adding quality gates.

samber/golang-database

Comprehensive guide for Go database access — parameterized queries, struct scanning, NULLable columns, transactions, isolation levels, SELECT FOR UPDATE, connection pool, batch processing, context propagation, and migration tooling. Use when writing, reviewing, or debugging Golang code that interacts with PostgreSQL, MariaDB, MySQL, or SQLite; for database testing; or for questions about database/sql, sqlx, or pgx. Does NOT generate database schemas or migration SQL.

samber/golang-data-structures

Golang data structures — slices (internals, capacity growth, preallocation, slices package), maps (internals, hash buckets, maps package), arrays, container/list/heap/ring, strings.Builder vs bytes.Buffer, generic collections, pointers (unsafe.Pointer, weak.Pointer), and copy semantics. Use when choosing or optimizing Go data structures, implementing generic containers, using container/ packages, unsafe or weak pointers, or questioning slice/map internals.

samber/golang-dependency-injection

Comprehensive guide for dependency injection (DI) in Golang. Covers why DI matters (testability, loose coupling, separation of concerns, lifecycle management), manual constructor injection, and DI library comparison (google/wire, uber-go/dig, uber-go/fx, samber/do). Use this skill when designing service architecture, setting up dependency injection, refactoring tightly coupled code, managing singletons or service factories, or when the user asks about inversion of control, service containers, or wiring dependencies in Go. For a specific DI library, → See `samber/cc-skills-golang@golang-google-wire`, `samber/cc-skills-golang@golang-uber-dig`, `samber/cc-skills-golang@golang-uber-fx`, or `samber/cc-skills-golang@golang-samber-do` skills.

samber/golang-dependency-management

Dependency management strategies for Golang projects — go.mod management, installing/upgrading packages, Minimal Version Selection, vulnerability scanning, outdated dependency tracking, binary size analysis, Dependabot/Renovate setup, conflict resolution, and go.work workspaces. Use when adding, removing, or upgrading Go dependencies, auditing vulnerabilities, resolving version conflicts, or setting up automated dependency updates.

samber/golang-design-patterns

Idiomatic Golang design patterns — functional options, constructors, error flow and cascading, resource management and lifecycle, graceful shutdown, resilience, architecture, dependency injection, data handling, streaming, and more. Apply when explicitly choosing between architectural patterns, implementing functional options, designing constructor APIs, setting up graceful shutdown, applying resilience patterns, or asking which idiomatic Go pattern fits a specific problem.

samber/golang-documentation

Comprehensive documentation guide for Golang projects, covering godoc comments, README, CONTRIBUTING, CHANGELOG, Go Playground, Example tests, API docs, and llms.txt. Use when writing or reviewing doc comments, documentation, adding code examples, setting up doc sites, or discussing documentation best practices. Triggers for both libraries and applications/CLIs.

samber/golang-error-handling

Idiomatic Golang error handling — creation, wrapping with %w, errors.Is/As, errors.Join, custom error types, sentinel errors, panic/recover, the single handling rule, structured logging with slog, HTTP request logging middleware, and samber/oops for production errors. Built to make logs usable at scale with log aggregation 3rd-party tools. Apply when creating, wrapping, inspecting, or logging errors in Go code. For samber/oops specifics → See `samber/cc-skills-golang@golang-samber-oops` skill; for slog handler ecosystem → See `samber/cc-skills-golang@golang-samber-slog` skill.

samber/golang-google-wire

Compile-time dependency injection in Golang using google/wire — wire.NewSet, wire.Build, wire.Bind (interface→concrete), wire.Struct, wire.Value, wire.InterfaceValue, wire.FieldsOf, cleanup functions, //go:build wireinject injector files, and generated wire_gen.go. Apply when using or adopting google/wire, when the codebase imports `github.com/google/wire`, or when wiring an application graph at compile time via `wire.Build`. For runtime DI with reflection, see `samber/cc-skills-golang@golang-uber-dig` skill.

samber/golang-gopls

Golang semantic code intelligence via `gopls`, the official Go language server — go-to-definition, find references, call/implementation hierarchy, workspace symbol search, package API discovery, diagnostics, safe rename, refactors (extract/inline/fill/rewrite code actions), formatting, and generated tests. Reaches an agent via gopls's own MCP server (`go_*` tools), Claude Code's native `LSP` tool, or the `gopls` CLI. Use when navigating or refactoring Go code — jumping to a definition, finding call sites before a rename, understanding a file's or package's dependencies, running diagnostics after an edit, or extracting/inlining/renaming. Not for the published ecosystem — packages not in your `go.mod`, versions, licenses, importers — → See `samber/cc-skills-golang@golang-pkg-go-dev` skill (`godig`). Not for a whole-tree vulnerability audit → See `samber/cc-skills-golang@golang-security` skill (`govulncheck`).

samber/golang-graphql

Implements GraphQL APIs in Golang using gqlgen or graphql-go. Apply when building GraphQL servers, designing schemas, writing resolvers, handling subscriptions, or integrating GraphQL with existing Go HTTP services. Also apply when the codebase imports `github.com/99designs/gqlgen` or `github.com/graph-gophers/graphql-go`.

samber/golang-grpc

Provides gRPC usage guidelines, protobuf organization, and production-ready patterns for Golang microservices. Use when implementing, reviewing, or debugging gRPC servers/clients, writing proto files, setting up interceptors, handling gRPC errors with status codes, configuring TLS/mTLS, testing with bufconn, or working with streaming RPCs.

samber/golang-how-to

Golang skills orchestrator — always active on any Golang coding, review, debug, or setup task. Reads the task context and loads the most relevant skills from samber/cc-skills-golang, often multiple at once: writing a gRPC service loads golang-grpc + golang-testing + golang-error-handling; debugging a panic loads golang-troubleshooting + golang-safety; auditing security loads golang-security + golang-lint + golang-safety. Also: disambiguates competing clusters when two skills seem to overlap (performance vs benchmark vs troubleshooting, samber/lo vs mo vs ro, DI cluster, safety vs security), and configures the project's agent-config file (CLAUDE.md, AGENTS.md, GEMINI.md, Cursor rules, or Copilot instructions) to force-trigger skills in a project (/golang-how-to configure).

samber/golang-lint

Linting best practices and golangci-lint configuration for Golang projects — running linters, configuring .golangci.yml, suppressing warnings with nolint directives, interpreting lint output, and selecting linters. Use when configuring golangci-lint, asking about lint warnings or nolint suppressions, setting up code quality tooling, or choosing linters. Also use when the user mentions golangci-lint, go vet, staticcheck, or revive.

samber/golang-modernize

Modernize Golang code to use recent language features, standard library improvements, and idiomatic patterns. Trigger proactively when writing or reviewing Go code and old-style patterns are detected, or when encountering a deprecation warning. Also use when the user explicitly asks for modernization, a Go version upgrade, or a CI/tooling refresh.

Verwandte Skills