{"id":"c8996450-b590-464e-905b-201542c14d7e","shortId":"g3sfuS","kind":"skill","title":"go-defensive","tagline":"Use when hardening Go code at API boundaries — copying slices/maps, verifying interface compliance, using defer for cleanup, time.Time/time.Duration, or avoiding mutable globals. Also use when reviewing for robustness concerns like missing cleanup or unsafe crypto usage, even if ","description":"# Go Defensive Programming Patterns\n\n## Defensive Checklist Priority\n\nWhen hardening code at API boundaries, check in this order:\n\n```\nReviewing an API boundary?\n├─ 1. Error handling     → Return errors; don't panic (see go-error-handling)\n├─ 2. Input validation   → Copy slices/maps received from callers\n├─ 3. Output safety      → Copy slices/maps before returning to callers\n├─ 4. Resource cleanup   → Use defer for Close/Unlock/Cancel\n├─ 5. Interface checks   → var _ Interface = (*Type)(nil) for compile-time verification\n├─ 6. Time correctness   → Use time.Time and time.Duration, not int/float\n├─ 7. Enum safety        → Start iota at 1 so zero-value is invalid\n└─ 8. Crypto safety      → crypto/rand for keys, never math/rand\n```\n\n---\n\n## Quick Reference\n\n| Pattern | Rule | Details |\n|---------|------|---------|\n| Boundary copies | Copy slices/maps on receive and return | [BOUNDARY-COPYING.md](references/BOUNDARY-COPYING.md) |\n| Defer cleanup | `defer f.Close()` right after `os.Open` | Below |\n| Interface check | `var _ I = (*T)(nil)` | See go-interfaces |\n| Time types | `time.Time` / `time.Duration`, never raw int | [TIME-ENUMS-TAGS.md](references/TIME-ENUMS-TAGS.md) |\n| Enum start | `iota + 1` so zero = invalid | Below |\n| Crypto rand | `crypto/rand` for keys, never `math/rand` | Below |\n| Must functions | Only at init; panic on failure | [MUST-FUNCTIONS.md](references/MUST-FUNCTIONS.md) |\n| Panic/recover | Never expose panics across packages | [PANIC-RECOVER.md](references/PANIC-RECOVER.md) |\n| Mutable globals | Replace with dependency injection | Below |\n\n---\n\n## Verify Interface Compliance\n\nUse compile-time checks to verify interface implementation. See **go-interfaces**: Interface Satisfaction Checks for the full pattern.\n\n```go\nvar _ http.Handler = (*Handler)(nil)\n```\n\n## Copy Slices and Maps at Boundaries\n\nSlices and maps contain pointers to underlying data. Copy at API boundaries to prevent unintended modifications.\n\n```go\n// Receiving: copy incoming slice\nd.trips = make([]Trip, len(trips))\ncopy(d.trips, trips)\n\n// Returning: copy map before returning\nresult := make(map[string]int, len(s.counters))\nfor k, v := range s.counters { result[k] = v }\n```\n\n> Read [references/BOUNDARY-COPYING.md](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.\n\n## Defer to Clean Up\n\nUse `defer` to clean up resources (files, locks). Avoids missed cleanup on multiple return paths.\n\n```go\np.Lock()\ndefer p.Unlock()\n\nif p.count < 10 {\n  return p.count\n}\np.count++\nreturn p.count\n```\n\nDefer overhead is negligible. Place `defer f.Close()` immediately after\n`os.Open` for clarity. Arguments to deferred functions are evaluated when\n`defer` executes, not when the function runs. Multiple defers execute in\nLIFO order.\n\n## Struct Field Tags\n\n> **Advisory**: Always add explicit field tags to structs that are marshaled or unmarshaled.\n\n```go\ntype User struct {\n    Name  string `json:\"name\"  yaml:\"name\"`\n    Email string `json:\"email\" yaml:\"email\"`\n}\n```\n\nField tags are a **serialization contract** — renaming a struct field without\nupdating the tag silently breaks wire compatibility. Treat tags as part of\nthe public API for any type that crosses a serialization boundary.\n\n## Start Enums at One\n\nStart enums at non-zero to distinguish uninitialized from valid values.\n\n```go\nconst (\n  Add Operation = iota + 1  // Add=1, zero value = uninitialized\n  Subtract\n  Multiply\n)\n```\n\n**Exception**: When zero is the sensible default (e.g., `LogToStdout = iota`).\n\n## Time, Struct Tags, and Embedding\n\n> Read [references/TIME-ENUMS-TAGS.md](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.\n\n## Avoid Mutable Globals\n\nInject dependencies instead of mutating package-level variables. This makes\ncode testable without global save/restore.\n\n```go\ntype signer struct {\n  now func() time.Time  // injected; tests replace with fixed time\n}\n\nfunc newSigner() *signer {\n  return &signer{now: time.Now}\n}\n```\n\n> Read [references/GLOBAL-STATE.md](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.\n\n## Crypto Rand\n\nDo not use `math/rand` or `math/rand/v2` to generate keys — this is a\n**security concern**. Time-seeded generators have predictable output.\n\n```go\nimport \"crypto/rand\"\n\nfunc Key() string { return rand.Text() }\n```\n\nFor text output, use `crypto/rand.Text` directly, or encode random bytes\nwith `encoding/hex` or `encoding/base64`.\n\n---\n\n## Panic and Recover\n\nUse `panic` only for truly unrecoverable situations. Library functions\nshould avoid panic.\n\n```go\nfunc safelyDo(work *Work) {\n    defer func() {\n        if err := recover(); err != nil {\n            log.Println(\"work failed:\", err)\n        }\n    }()\n    do(work)\n}\n```\n\n**Key rules:**\n- Never expose panics across package boundaries — always convert to errors\n- Acceptable to panic in `init()` if a library truly cannot set itself up\n- Use recover to isolate panics in server goroutine handlers\n\n> Read [references/PANIC-RECOVER.md](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.\n\n## Must Functions\n\n`Must` functions panic on error — use them **only** during program\ninitialization where failure means the program cannot run.\n\n```go\nvar validID = regexp.MustCompile(`^[a-z][a-z0-9-]{0,62}$`)\nvar tmpl = template.Must(template.ParseFiles(\"index.html\"))\n```\n\n> Read [references/MUST-FUNCTIONS.md](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.\n\n---\n\n## Related Skills\n\n- **Error handling**: See [go-error-handling](../go-error-handling/SKILL.md) when choosing between returning errors and panicking, or wrapping errors at boundaries\n- **Concurrency safety**: See [go-concurrency](../go-concurrency/SKILL.md) when protecting shared state with mutexes, atomics, or channels\n- **Interface checks**: See [go-interfaces](../go-interfaces/SKILL.md) when adding compile-time interface satisfaction checks (`var _ I = (*T)(nil)`)\n- **Data structure copying**: See [go-data-structures](../go-data-structures/SKILL.md) when working with slice/map internals or pointer aliasing","tags":["defensive","golang","skills","cxuu","agent-skills","ai-agent","ai-assistant","claude","claude-code","codex","cursor","llm"],"capabilities":["skill","source-cxuu","skill-go-defensive","topic-agent-skills","topic-ai-agent","topic-ai-assistant","topic-claude","topic-claude-code","topic-codex","topic-cursor","topic-golang","topic-llm"],"categories":["golang-skills"],"synonyms":[],"warnings":[],"endpointUrl":"https://skills.sh/cxuu/golang-skills/go-defensive","protocol":"skill","transport":"skills-sh","auth":{"type":"none","details":{"cli":"npx skills add cxuu/golang-skills","source_repo":"https://github.com/cxuu/golang-skills","install_from":"skills.sh"}},"qualityScore":"0.491","qualityRationale":"deterministic score 0.49 from registry signals: · indexed on github topic:agent-skills · 82 github stars · SKILL.md body (6,597 chars)","verified":false,"liveness":"unknown","lastLivenessCheck":null,"agentReviews":{"count":0,"score_avg":null,"cost_usd_avg":null,"success_rate":null,"latency_p50_ms":null,"narrative_summary":null,"summary_updated_at":null},"enrichmentModel":"deterministic:skill-github:v1","enrichmentVersion":1,"enrichedAt":"2026-05-02T12:55:18.056Z","embedding":null,"createdAt":"2026-04-18T22:13:11.871Z","updatedAt":"2026-05-02T12:55:18.056Z","lastSeenAt":"2026-05-02T12:55:18.056Z","tsv":"'/go-concurrency/skill.md':827 '/go-data-structures/skill.md':864 '/go-error-handling/skill.md':808 '/go-interfaces/skill.md':843 '/time.duration,':23 '0':766 '1':65,129,189,484,486 '10':359 '2':78 '3':86 '4':95 '5':102 '6':114 '62':767 '7':123 '8':136 '9':765 'a-z':759 'a-z0':762 'accept':687 'across':216,680 'ad':518,845 'add':402,481,485 'advisori':400 'alias':872 'also':28 'alway':401,683 'api':10,55,63,271,319,454 'appropri':582,785 'argument':377 'atom':834 'avoid':25,346,533,655 'boundari':11,56,64,149,260,272,320,462,682,820 'boundary-copying.md':157 'break':444 'byte':637 'call':789 'caller':85,94 'cannot':696,753 'channel':836 'check':57,104,168,234,245,838,851 'checklist':49 'choos':810 'clariti':376 'clean':336,341 'cleanup':20,37,97,160,348 'close/unlock/cancel':101 'code':8,53,547 'compat':446 'compil':111,232,847 'compile-tim':110,231,846 'complianc':16,229 'concern':34,612 'concurr':821,826 'const':480 'contain':264 'contract':434 'control':724 'convert':684 'copi':12,81,89,150,151,255,269,279,287,291,314,325,858 'correct':116 'cross':459 'crypto':40,137,194,597 'crypto/rand':139,196,622 'crypto/rand.text':632 'custom':778 'd.trips':282,288 'data':268,856,862 'decid':322,525,576,730,781 'default':498,586 'defens':3,45,48,324 'defer':18,99,159,161,334,339,355,365,370,379,384,392,662 'depend':224,537,595 'design':583 'detail':148 'direct':633 'distinguish':474 'e.g':499 'email':423,426,428 'emb':528 'embed':506 'encod':635 'encoding/base64':641 'encoding/hex':639 'enum':124,186,464,468 'err':665,667,672 'error':66,69,76,686,741,801,806,813,818 'evalu':382 'even':42 'except':492 'execut':385,393 'explicit':403 'expos':214,678 'f.close':162,371 'fail':671 'failur':209,749 'fallibl':793 'field':398,404,429,438,519 'file':344 'fix':563 'flow':725 'full':248 'func':557,565,623,658,663 'function':203,380,389,653,736,738,780 'generat':606,616 'given':788 'global':27,221,535,550,579,593 'go':2,7,44,75,175,241,250,277,353,413,479,552,620,657,755,805,825,841,861 'go-concurr':824 'go-data-structur':860 'go-defens':1 'go-error-handl':74,804 'go-interfac':174,240,840 'goroutin':707 'handl':67,77,802,807 'handler':253,708 'harden':6,52 'helper':798 'http':717 'http.handler':252 'immedi':372 'implement':238 'import':621 'incom':280 'index.html':772 'init':206,691 'initi':747,794 'inject':225,536,559,596 'input':79 'instead':514,538 'int':183,299,517 'int/float':122 'interfac':15,103,106,167,176,228,237,242,243,837,842,849 'intern':723,869 'invalid':135,192 'iota':127,188,483,501 'isol':703 'json':419,425 'k':303,308 'key':141,198,607,624,675 'len':285,300 'level':543 'librari':652,694 'lifo':395 'like':35 'lock':345 'log.fatal':732 'log.println':669 'logtostdout':500 'make':283,296,546 'map':258,263,292,297,317 'marshal':410,522 'math/rand':143,200,602 'math/rand/v2':604 'mean':750 'mechan':726 'miss':36,347 'modif':276 'multipl':350,391 'multipli':491 'must':202,735,737,779,783 'must-functions.md':210 'mutabl':26,220,534,592 'mutat':540 'mutex':833 'name':417,420,422 'necessari':327 'neglig':368 'never':142,181,199,213,677 'new':585 'newsign':566 'nil':108,172,254,668,855 'non':471 'non-zero':470 'one':466 'oper':482 'order':60,396 'os.open':165,374 'output':87,619,630 'overhead':366 'p.count':358,361,362,364 'p.lock':354 'p.unlock':356 'packag':217,542,587,681 'package-level':541 'panic':72,207,215,642,646,656,679,689,704,714,720,734,739 'panic-recover.md':218 'panic/recover':212 'panick':797,815 'parser':728 'part':450 'path':352 'pattern':47,146,249,589 'place':369 'pointer':265,871 'predict':618 'prevent':274 'prioriti':50 'program':46,746,752 'protect':829 'public':453,531 'quick':144 'rand':195,598 'rand.text':627 'random':636 'rang':305 'raw':182,516 'read':310,507,572,709,773 'receiv':83,154,278 'recov':644,666,701 'recoveri':715 'refer':145 'references/boundary-copying.md':158,311,312 'references/global-state.md':573,574 'references/must-functions.md':211,774,775 'references/panic-recover.md':219,710,711 'references/time-enums-tags.md':185,508,509 'regexp.mustcompile':758 'relat':799 'renam':435 'replac':222,561,591 'resourc':96,343 'result':295,307 'return':68,92,156,290,294,351,360,363,568,626,812 'review':31,61 'right':163 'robust':33 'rule':147,676 'run':390,754 's.counters':301,306 'safelydo':659 'safeti':88,125,138,822 'satisfact':244,850 'save/restore':551 'secur':611 'see':73,173,239,803,823,839,859 'seed':615 'sensibl':497 'serial':433,461 'server':706,718 'set':697 'share':830 'signer':554,567,569 'silent':443 'site':790 'situat':651 'skill':800 'skill-go-defensive' 'skip':333 'slice':256,261,281,315 'slice/map':868 'slices/maps':13,82,90,152 'source-cxuu' 'start':126,187,463,467 'state':588,831 'string':298,418,424,625 'struct':397,407,416,437,503,523,532,555 'structur':857,863 'subtract':490 'tag':399,405,430,442,448,504,520 'template.must':770 'template.parsefiles':771 'test':560 'testabl':548 'text':629 'time':112,115,177,233,502,564,614,848 'time-enums-tags.md':184 'time-seed':613 'time.duration':120,180,513 'time.now':571 'time.time':22,118,179,512,558 'time.time/time.duration,':21 'tmpl':769 'topic-agent-skills' 'topic-ai-agent' 'topic-ai-assistant' 'topic-claude' 'topic-claude-code' 'topic-codex' 'topic-cursor' 'topic-golang' 'topic-llm' 'treat':447 'trip':284,286,289 'truli':649,695 'type':107,178,414,457,529,553 'under':267 'uniniti':475,489 'unintend':275 'unmarsh':412 'unrecover':650 'unsaf':39 'updat':440 'usag':41 'use':4,17,29,98,117,230,338,511,601,631,645,700,719,742 'user':415 'v':304,309 'valid':80,477 'validid':757 'valu':133,478,488 'var':105,169,251,756,768,852 'variabl':544,580 'verif':113 'verifi':14,227,236 'vs':328 'whether':526,577,782 'wire':445 'without':439,549 'work':660,661,670,674,866 'wrap':792,817 'write':713,777 'yaml':421,427 'z':761 'z0':764 'zero':132,191,472,487,494 'zero-valu':131","prices":[{"id":"118d0b5d-1f1a-4f5a-9eb3-74ddc4fe9bbe","listingId":"c8996450-b590-464e-905b-201542c14d7e","amountUsd":"0","unit":"free","nativeCurrency":null,"nativeAmount":null,"chain":null,"payTo":null,"paymentMethod":"skill-free","isPrimary":true,"details":{"org":"cxuu","category":"golang-skills","install_from":"skills.sh"},"createdAt":"2026-04-18T22:13:11.871Z"}],"sources":[{"listingId":"c8996450-b590-464e-905b-201542c14d7e","source":"github","sourceId":"cxuu/golang-skills/go-defensive","sourceUrl":"https://github.com/cxuu/golang-skills/tree/main/skills/go-defensive","isPrimary":false,"firstSeenAt":"2026-04-18T22:13:11.871Z","lastSeenAt":"2026-05-02T12:55:18.056Z"}],"details":{"listingId":"c8996450-b590-464e-905b-201542c14d7e","quickStartSnippet":null,"exampleRequest":null,"exampleResponse":null,"schema":null,"openapiUrl":null,"agentsTxtUrl":null,"citations":[],"useCases":[],"bestFor":[],"notFor":[],"kindDetails":{"org":"cxuu","slug":"go-defensive","github":{"repo":"cxuu/golang-skills","stars":82,"topics":["agent-skills","ai-agent","ai-assistant","claude","claude-code","codex","cursor","go","golang","llm"],"license":"apache-2.0","html_url":"https://github.com/cxuu/golang-skills","pushed_at":"2026-03-15T19:32:10Z","description":"AI Agent Skills for idiomatic, production-ready Go code, distilled from Google, Uber, Community","skill_md_sha":"798cce228eee0a98569d83ccd0b5df0488c664f8","skill_md_path":"skills/go-defensive/SKILL.md","default_branch":"main","skill_tree_url":"https://github.com/cxuu/golang-skills/tree/main/skills/go-defensive"},"layout":"multi","source":"github","category":"golang-skills","frontmatter":{"name":"go-defensive","license":"Apache-2.0","description":"Use when hardening Go code at API boundaries — copying slices/maps, verifying interface compliance, using defer for cleanup, time.Time/time.Duration, or avoiding mutable globals. Also use when reviewing for robustness concerns like missing cleanup or unsafe crypto usage, even if the user doesn't mention \"defensive programming.\" Does not cover error handling strategy (see go-error-handling).","compatibility":"Uses crypto/rand.Text (Go 1.24+) in examples"},"skills_sh_url":"https://skills.sh/cxuu/golang-skills/go-defensive"},"updatedAt":"2026-05-02T12:55:18.056Z"}}