From golang-skills
Hardens Go APIs with defensive patterns: copies slices/maps at boundaries, verifies interfaces, defers cleanup, uses time.Time/Duration, enum safety, crypto/rand, avoids mutable globals.
npx claudepluginhub cxuu/golang-skills --plugin golang-skillsThis skill uses the workspace's default tool permissions.
When hardening code at API boundaries, check in this order:
Enforces defensive Go coding to prevent nil panics, data corruption, append aliasing, map/channel issues, defer loop pitfalls, numeric truncation, and float comparison bugs. Use for Go code writing or review.
Provides idiomatic Go patterns and best practices for writing, reviewing, refactoring Go code, and designing packages. Covers simplicity, zero values, interfaces, and error handling.
Writes, reviews, and debugs idiomatic Go code covering error handling, testing, concurrency, security, gRPC APIs with AIP, program design, and best practices like table-driven tests and error wrapping.
Share bugs, ideas, or general feedback.
When hardening code at API boundaries, check in this order:
Reviewing an API boundary?
├─ 1. Error handling → Return errors; don't panic (see go-error-handling)
├─ 2. Input validation → Copy slices/maps received from callers
├─ 3. Output safety → Copy slices/maps before returning to callers
├─ 4. Resource cleanup → Use defer for Close/Unlock/Cancel
├─ 5. Interface checks → var _ Interface = (*Type)(nil) for compile-time verification
├─ 6. Time correctness → Use time.Time and time.Duration, not int/float
├─ 7. Enum safety → Start iota at 1 so zero-value is invalid
└─ 8. Crypto safety → crypto/rand for keys, never math/rand
| Pattern | Rule | Details |
|---|---|---|
| Boundary copies | Copy slices/maps on receive and return | BOUNDARY-COPYING.md |
| Defer cleanup | defer f.Close() right after os.Open | Below |
| Interface check | var _ I = (*T)(nil) | See go-interfaces |
| Time types | time.Time / time.Duration, never raw int | TIME-ENUMS-TAGS.md |
| Enum start | iota + 1 so zero = invalid | Below |
| Crypto rand | crypto/rand for keys, never math/rand | Below |
| Must functions | Only at init; panic on failure | MUST-FUNCTIONS.md |
| Panic/recover | Never expose panics across packages | PANIC-RECOVER.md |
| Mutable globals | Replace with dependency injection | Below |
Use compile-time checks to verify interface implementation. See go-interfaces: Interface Satisfaction Checks for the full pattern.
var _ http.Handler = (*Handler)(nil)
Slices and maps contain pointers to underlying data. Copy at API boundaries to prevent unintended modifications.
// Receiving: copy incoming slice
d.trips = make([]Trip, len(trips))
copy(d.trips, trips)
// Returning: copy map before returning
result := make(map[string]int, len(s.counters))
for k, v := range s.counters { result[k] = v }
Read references/BOUNDARY-COPYING.md when copying slices or maps at API boundaries, or deciding when defensive copies are necessary vs. when they can be skipped.
Use defer to clean up resources (files, locks). Avoids missed cleanup on multiple return paths.
p.Lock()
defer p.Unlock()
if p.count < 10 {
return p.count
}
p.count++
return p.count
Defer overhead is negligible. Place defer f.Close() immediately after
os.Open for clarity. Arguments to deferred functions are evaluated when
defer executes, not when the function runs. Multiple defers execute in
LIFO order.
Advisory: Always add explicit field tags to structs that are marshaled or unmarshaled.
type User struct {
Name string `json:"name" yaml:"name"`
Email string `json:"email" yaml:"email"`
}
Field tags are a serialization contract — renaming a struct field without updating the tag silently breaks wire compatibility. Treat tags as part of the public API for any type that crosses a serialization boundary.
Start enums at non-zero to distinguish uninitialized from valid values.
const (
Add Operation = iota + 1 // Add=1, zero value = uninitialized
Subtract
Multiply
)
Exception: When zero is the sensible default (e.g., LogToStdout = iota).
Read references/TIME-ENUMS-TAGS.md when using
time.Time/time.Durationinstead of raw ints, adding field tags to marshaled structs, or deciding whether to embed types in public structs.
Inject dependencies instead of mutating package-level variables. This makes code testable without global save/restore.
type signer struct {
now func() time.Time // injected; tests replace with fixed time
}
func newSigner() *signer {
return &signer{now: time.Now}
}
Read references/GLOBAL-STATE.md when deciding whether a global variable is appropriate, designing the New() + Default() package state pattern, or replacing mutable globals with dependency injection.
Do not use math/rand or math/rand/v2 to generate keys — this is a
security concern. Time-seeded generators have predictable output.
import "crypto/rand"
func Key() string { return rand.Text() }
For text output, use crypto/rand.Text directly, or encode random bytes
with encoding/hex or encoding/base64.
Use panic only for truly unrecoverable situations. Library functions
should avoid panic.
func safelyDo(work *Work) {
defer func() {
if err := recover(); err != nil {
log.Println("work failed:", err)
}
}()
do(work)
}
Key rules:
init() if a library truly cannot set itself upRead references/PANIC-RECOVER.md when writing panic recovery in HTTP servers, using panic as an internal control flow mechanism in parsers, or deciding between log.Fatal and panic.
Must functions panic on error — use them only during program
initialization where failure means the program cannot run.
var validID = regexp.MustCompile(`^[a-z][a-z0-9-]{0,62}$`)
var tmpl = template.Must(template.ParseFiles("index.html"))
Read references/MUST-FUNCTIONS.md when writing custom Must functions, deciding whether Must is appropriate for a given call site, or wrapping fallible initialization in a panicking helper.
var _ I = (*T)(nil))