go-defensive

cxuu/golang-skills · updated Apr 8, 2026

MDX-style export adds YAML metadata + attribution linking explainx.ai and this canonical listing URL.

$npx skills add https://github.com/cxuu/golang-skills --skill go-defensive
0 commentsdiscussion
summary

When hardening code at API boundaries, check in this order:

skill.md

Go Defensive Programming Patterns

Defensive Checklist Priority

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

Quick Reference

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

Verify Interface Compliance

Use compile-time checks to verify interface implementation. See go-interfaces: Interface Satisfaction Checks for the full pattern.

var _ http.Handler = (*Handler)(nil)

Copy Slices and Maps at Boundaries

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.

Defer to Clean Up

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.

Struct Field Tags

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 One

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

Time, Struct Tags, and Embedding

Read references/TIME-ENUMS-TAGS.md when using time.Time/time.Duration instead of raw ints, adding field tags to marshaled structs, or deciding whether to embed types in public structs.

Avoid Mutable Globals

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.

Crypto Rand

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.


Panic and Recover

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:

  • Never expose panics across package boundaries — always convert to errors
  • Acceptable to panic in init() if a library truly cannot set itself up
  • Use recover to isolate panics in server goroutine handlers

Read 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

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.


Related Skills

  • Error handling: See go-error-handling when choosing between returning errors and panicking, or wrapping errors at boundaries
  • Concurrency safety: See go-concurrency when protecting shared state with mutexes, atomics, or channels
  • Interface checks: See go-interfaces when adding compile-time interface satisfaction checks (var _ I = (*T)(nil))
  • Data structure copying: See go-data-structures when working with slice/map internals or pointer aliasing
how to use go-defensive

How to use go-defensive on Cursor

AI-first code editor with Composer

1

Prerequisites

Before installing skills in Cursor, ensure your development environment meets these requirements:

  • Cursor installed and configured on your development machine
  • Node.js version 16.0+ with npm package manager (verify with node --version)
  • Active project directory or workspace where you want to add go-defensive
2

Execute installation command

Execute the skills CLI command in your project's root directory to begin installation:

$npx skills add https://github.com/cxuu/golang-skills --skill go-defensive

The skills CLI fetches go-defensive from GitHub repository cxuu/golang-skills and configures it for Cursor.

3

Select Cursor when prompted

The CLI will show a list of available agents. Use arrow keys to navigate and space to select Cursor:

◆ Which agents do you want to install to?
│ ── Universal (.agents/skills) ── always included ────
│ • Amp
│ • Antigravity
│ • Cline
│ • Codex
│ ●Cursor(selected)
│ • Cursor
│ • Windsurf
4

Verify installation

Confirm successful installation by checking the skill directory location:

.cursor/skills/go-defensive

Reload or restart Cursor to activate go-defensive. Access the skill through slash commands (e.g., /go-defensive) or your agent's skill management interface.

Security & Verification Notice

We perform automated surface-level scans (Gen AI Scanner, Socket, Snyk) during installation. These checks detect common vulnerabilities but do not guarantee complete security. Always review skill source code and verify the publisher's reputation before production use.

Skills execute code in your development environment. Always verify the publisher's identity, review recent commits, and test in isolated environments before production deployment.

List & Monetize Your Skill

Submit your Claude Code skill and start earning

GET_STARTED →

Use Cases

Task Automation & Efficiency

Automate repetitive workflows and reduce manual effort

Example

Generate reports, summarize documents, draft communications

Save 3-5 hours per week on routine tasks

Knowledge Enhancement

Learn new skills, understand complex topics, get expert guidance

Example

Explain concepts, provide examples, suggest learning resources

Accelerate learning and skill development by 2x

Quality Improvement

Enhance output quality through reviews, suggestions, and refinements

Example

Review drafts, suggest improvements, catch errors

Improve work quality by 30-40% with less effort

Implementation Guide

Prerequisites

  • Claude Desktop or compatible AI client with skill support
  • Clear understanding of task or problem to solve
  • Willingness to iterate and refine outputs

Time Estimate

15-45 minutes depending on use case complexity

Installation Steps

  1. 1.Install skill using provided installation command
  2. 2.Test with simple use case relevant to your work
  3. 3.Evaluate output quality and relevance
  4. 4.Iterate on prompts to improve results
  5. 5.Integrate into regular workflow if valuable

Common Pitfalls

  • Expecting perfect results without iteration
  • Not providing enough context in prompts
  • Using skill for tasks outside its intended scope
  • Accepting outputs without review and validation

Best Practices

✓ Do

  • +Start with clear, specific prompts
  • +Provide relevant context and constraints
  • +Review and refine all outputs before using
  • +Iterate to improve output quality
  • +Document successful prompt patterns

✗ Don't

  • Don't use without understanding skill limitations
  • Don't skip validation of outputs
  • Don't share sensitive information in prompts
  • Don't expect skill to replace human judgment

💡 Pro Tips

  • Be specific about desired format and style
  • Ask for multiple options to choose from
  • Request explanations to understand reasoning
  • Combine AI efficiency with human expertise

When to Use This

✓ Use When

Use when skill capabilities match your task, clear ROI on time saved, and you can validate outputs. Best for repetitive tasks, learning, and quality improvement.

✗ Avoid When

Avoid when task requires deep expertise you can't validate, involves sensitive decisions, or when learning process is more valuable than speed of completion.

Learning Path

  1. 1Familiarize yourself with skill capabilities and limitations
  2. 2Start with low-risk, non-critical tasks
  3. 3Progress to more complex and valuable use cases
  4. 4Build expertise through regular use and experimentation

Discussion

Product Hunt–style comments (not star reviews)
  • No comments yet — start the thread.
general reviews

Ratings

4.751 reviews
  • Ganesh Mohane· Dec 28, 2024

    go-defensive has been reliable in day-to-day use. Documentation quality is above average for community skills.

  • Sophia Lopez· Dec 12, 2024

    Useful defaults in go-defensive — fewer surprises than typical one-off scripts, and it plays nicely with `npx skills` flows.

  • Anaya Gill· Dec 4, 2024

    I recommend go-defensive for anyone iterating fast on agent tooling; clear intent and a small, reviewable surface area.

  • Liam Bansal· Nov 23, 2024

    Useful defaults in go-defensive — fewer surprises than typical one-off scripts, and it plays nicely with `npx skills` flows.

  • Sakshi Patil· Nov 19, 2024

    Solid pick for teams standardizing on skills: go-defensive is focused, and the summary matches what you get after install.

  • Jin Kim· Nov 3, 2024

    I recommend go-defensive for anyone iterating fast on agent tooling; clear intent and a small, reviewable surface area.

  • Arya Haddad· Oct 26, 2024

    go-defensive reduced setup friction for our internal harness; good balance of opinion and flexibility.

  • Jin Rao· Oct 22, 2024

    go-defensive reduced setup friction for our internal harness; good balance of opinion and flexibility.

  • Emma Abebe· Oct 14, 2024

    go-defensive is among the better-maintained entries we tried; worth keeping pinned for repeat workflows.

  • Chaitanya Patil· Oct 10, 2024

    We added go-defensive from the explainx registry; install was straightforward and the SKILL.md answered most questions upfront.

showing 1-10 of 51

1 / 6