[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7EJXKWAJ0V38P8NJ7ABAVWN":3,"skill-same:01M7EJXKWAJ0V38P8NJ7ABAVWN":78},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":34,"commitSha":35,"skillDirectory":36,"forksCount":37,"repositoryHtmlUrl":38,"repositoryHomepageUrl":6,"ownerHtmlUrl":39,"ownerBlogUrl":6,"ownerDescription":40,"updatedAt":41,"install":42,"resources":55},"01M7EJXKWAJ0V38P8NJ7ABAVWN","go",null,"Use when writing, reviewing, testing, or shipping Go code and HTTP services: idioms, `%w` error wrapping, goroutine\u002Fcontext\u002Ferrgroup concurrency, net\u002Fhttp 1.22 routing, log\u002Fslog, project layout, table-driven tests, Go hardening. NOT language-agnostic threat modeling (that is `secure-coding`), NOT Dockerfile\u002FCI shipping (that is `deployment`).","lza6\u002FArmor-piercing-system-prompts","lza6","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F128880206?v=4","01M7EB3K7WPX5T28EJ2NVHE6EG","Chinese-tingfeng","01M7EB3K97E1KQ16QWKJMFNGX8",11,"MIT","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F04-安全渗透\u002Fgo\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: go\ndescription: \"Use when writing, reviewing, testing, or shipping Go code and HTTP services: idioms, `%w` error wrapping, goroutine\u002Fcontext\u002Ferrgroup concurrency, net\u002Fhttp 1.22 routing, log\u002Fslog, project layout, table-driven tests, Go hardening. NOT language-agnostic threat modeling (that is `secure-coding`), NOT Dockerfile\u002FCI shipping (that is `deployment`).\"\ntags: [go, golang, http, backend, service]\nrecommends: [postgresdb, secure-coding, deployment]\norigin: risco\n---\n\n# Idiomatic Go services\n\nTargets **Go 1.22+** (Go 1.26 is the current stable release): enhanced `net\u002Fhttp` routing\n(`mux.HandleFunc(\"GET \u002Fusers\u002F{id}\", h)` + `r.PathValue`), `log\u002Fslog` structured\nlogging, and fixed loop-variable semantics (no more `tt := tt`).\n\n> **⚠️ SDD new-feature gate — read this first.** If this skill fired on a **new, non-trivial feature or behaviour change** and there is **no approved spec + plan** under `02-DOCS\u002Fwiki\u002Fsdd\u002F`, STOP — do **not** write feature code yet. Hand off to `..\u002Fspecify\u002FSKILL.md` first: it runs brainstorm → spec → plan → tasks before any code, then routes back here once the plan is approved. Build here directly only for a genuinely one-line \u002F low-risk change. Method: `..\u002Fsdd\u002FSKILL.md`.\n\n## Boundary\n\nGo error handling and HTTP contract design (status-code taxonomy, REST resource naming) live\n**here** — this skill is the canonical authority for both in Go. Delegate outward:\n\n- Language-agnostic abuse\u002Fauthz review, threat modeling, OWASP-class bugs ->\n  [`secure-coding`](..\u002Fsecure-coding\u002FSKILL.md). This skill keeps the Go-specific controls:\n  SQL params, server timeouts, `govulncheck`, TLS defaults.\n- Containerfile \u002F k8s \u002F CI pipeline authoring -> [`deployment`](..\u002Fdeployment\u002FSKILL.md).\n  This skill ships only a Docker note + `ldflags`.\n- Recording per-project conventions in a workspace wiki -> [`harness`](..\u002Fharness\u002FSKILL.md)\n  (see \"Project grounding\" below).\n\nNon-service Go (CLI tooling, codegen, ML): the patterns apply, but the HTTP\u002Fproduction half\nis irrelevant.\n\n## Idioms\n\n**Useful zero value.** Design types so the zero value works before any constructor.\n\n```go\n\u002F\u002F Good: zero-value Counter is ready; the zero-value mutex is unlocked. var b bytes.Buffer too.\ntype Counter struct {\n\tmu sync.Mutex\n\tn  int\n}\n\nfunc (c *Counter) Inc() { c.mu.Lock(); c.n++; c.mu.Unlock() }\n\n\u002F\u002F Bad: nil map field panics on first write (assignment to entry in nil map); hidden init step.\ntype Registry struct{ items map[string]int }\n\nfunc (r *Registry) Add(k string) { r.items[k]++ } \u002F\u002F panic if items was never make()'d\n```\n\n**Accept interfaces, return structs.** Return the concrete type; declare the interface\nwhere it is consumed.\n\n```go\ntype UserStore interface { \u002F\u002F declared in package service - only what it needs\n\tGetUser(ctx context.Context, id string) (*User, error)\n}\nfunc NewService(s UserStore) *Service { return &Service{store: s} } \u002F\u002F Good: return *Service\n\u002F\u002F Bad: func NewService(s UserStore) UserStore - returning the interface hides the type.\n```\n\n**Functional options.** Defaults first, then apply options.\n\n```go\ntype Server struct {\n\taddr    string\n\ttimeout time.Duration\n\tlogger  *slog.Logger\n}\ntype Option func(*Server)\n\nfunc WithTimeout(d time.Duration) Option { return func(s *Server) { s.timeout = d } }\nfunc WithLogger(l *slog.Logger) Option   { return func(s *Server) { s.logger = l } }\n\nfunc NewServer(addr string, opts ...Option) *Server {\n\ts := &Server{addr: addr, timeout: 30 * time.Second, logger: slog.Default()} \u002F\u002F defaults first\n\tfor _, opt := range opts {\n\t\topt(s)\n\t}\n\treturn s\n}\n```\n\nUse a plain `Config` struct once options exceed ~5; options are for optional, composable\ntuning, not required fields.\n\n**Embedding for composition.** Embed to borrow a behavior, not to fake inheritance.\n\n```go\n\u002F\u002F Good: the service gets .Info\u002F.Error for free from the embedded logger.\ntype Service struct {\n\t*slog.Logger\n\tstore UserStore\n}\n\u002F\u002F Bad: deep type trees (Base -> Middle -> Leaf) modeling \"is-a\" inheritance - avoid.\n```\n\n**Early return.** Clear over clever: invert the error and `return`; keep the happy path flat\n(no arrow code).\n\n```go\n\u002F\u002F Good: each failure returns immediately; the success path is unindented.\nfunc save(ctx context.Context, u *User) error {\n\tif u == nil {\n\t\treturn errors.New(\"nil user\")\n\t}\n\tif err := validate(u); err != nil {\n\t\treturn fmt.Errorf(\"validate: %w\", err)\n\t}\n\treturn store.Put(ctx, u)\n}\n\u002F\u002F Bad: if u != nil { if err := validate(u); err == nil { ... } else { ... } } - arrow code.\n```\n\n**No package-level mutable state.** Inject via constructor (`func New(db *sql.DB) *Server`),\nnever a global `var db *sql.DB` opened in `init()` - globals couple everything and kill\ntestability.\n\n**Receivers.** Pick value or pointer per type and stay consistent across its method set;\nmutating \u002F large \u002F contains-`sync` -> pointer.\n\n**Go 1.22 loopvar.** Loop variables are per-iteration now. Stop emitting the workaround:\ninside `for _, tt := range tests` the line `\u002F\u002F tt := tt` is obsolete - DELETE it.\n\n## Errors\n\n**Sentinel vs typed.** Sentinels for identity; typed errors for data.\n\n```go\nvar ErrNotFound = errors.New(\"not found\")         \u002F\u002F sentinel: identity\ntype ValidationError struct{ Field, Msg string }  \u002F\u002F typed: carries data\nfunc (e *ValidationError) Error() string { return fmt.Sprintf(\"%s: %s\", e.Field, e.Msg) }\n```\n\n**Wrap and classify.** Wrap every crossed boundary with `%w`; never compare message strings.\n\n```go\nerr := fmt.Errorf(\"find user %s: %w\", id, ErrNotFound)\nif errors.Is(err, ErrNotFound) { \u002F* sentinel match through the wrap chain *\u002F }\nvar verr *ValidationError\nif errors.As(err, &verr) { \u002F* typed match: verr.Field, verr.Msg *\u002F }\njoined := errors.Join(err1, err2) \u002F\u002F 1.20+: aggregate; Is\u002FAs traverse both\n```\n\n**3-layer boundary (the canonical flow).** Repo wraps the driver sentinel into a domain\nsentinel; service passes it through; handler classifies once and maps to a status, logging\nonly the unexpected.\n\n```go\n\u002F\u002F repository: translate sql.ErrNoRows into a domain sentinel, keep the chain.\nfunc (r *Repo) GetUser(ctx context.Context, id string) (*User, error) {\n\tvar u User\n\terr := r.db.QueryRowContext(ctx, \"SELECT id, name FROM users WHERE id = $1\", id).\n\t\tScan(&u.ID, &u.Name)\n\tif errors.Is(err, sql.ErrNoRows) {\n\t\treturn nil, fmt.Errorf(\"user %s: %w\", id, ErrNotFound)\n\t}\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"query user %s: %w\", id, err)\n\t}\n\treturn &u, nil\n}\n\n\u002F\u002F handler: classify once, map to HTTP status.\nfunc (h *Handler) getUser(w http.ResponseWriter, r *http.Request) {\n\tu, err := h.svc.GetUser(r.Context(), r.PathValue(\"id\"))\n\tswitch {\n\tcase err == nil:\n\t\twriteJSON(w, http.StatusOK, u)\n\tcase errors.Is(err, ErrNotFound):\n\t\thttp.Error(w, \"not found\", http.StatusNotFound)\n\tdefault:\n\t\tslog.Error(\"get user\", \"err\", err)\n\t\thttp.Error(w, \"internal error\", http.StatusInternalServerError)\n\t}\n}\n```\n\nFull handler adapter (error-returning `apiHandler`) -> `references\u002Fhttp-services.md`.\n\n**`defer` + named return** to capture `Close()` errors:\n\n```go\nfunc read(name string) (err error) {\n\tf, e := os.Open(name)\n\tif e != nil {\n\t\treturn e\n\t}\n\tdefer func() { err = errors.Join(err, f.Close()) }() \u002F\u002F capture Close() into the return\n\treturn nil\n}\n```\n\n## Concurrency (essentials)\n\n`context.Context` is the **first** param of every call, never stored in a struct, never `nil`\n(use `context.TODO()` while wiring). Bound work with a context deadline; bound concurrency\nwith `errgroup` — the derived `ctx` cancels siblings on first error, and `g.SetLimit(n)` caps\nin-flight goroutines:\n\n```go\ng, ctx := errgroup.WithContext(ctx)\ng.SetLimit(8)\nfor _, id := range ids {\n\tg.Go(func() error { return process(ctx, id) }) \u002F\u002F Go 1.22+: no id := id needed\n}\nerr := g.Wait()\n```\n\nThree rules cover most service code: every goroutine needs a known exit path (a started\ngoroutine you cannot stop is a leak); an unbuffered `ch \u003C- v` with no receiver after a cancel\nblocks forever, so buffer it and `select` on `ctx.Done()`; **run `-race` in CI**. Low-level\nneeds map to `sync.Once` (lazy init), `sync.RWMutex` (read-heavy state), `sync\u002Fatomic`\n(`atomic.Int64` counters).\n\nFull implementations — context plumbing, channel\u002Fselect patterns, leak detection, worker\npools, pipelines, fan-in\u002Fout, semaphores, `singleflight`, and a `withRetry` helper (backoff +\nfull jitter, `ctx`-aware, **never retries 4xx**) -> `references\u002Fconcurrency.md`.\n\n## HTTP services (essentials)\n\nGo 1.22 routed mux — method and path live in the pattern; the `error`-returning adapter\ncentralizes status mapping:\n\n```go\nmux := http.NewServeMux()\nmux.HandleFunc(\"GET \u002Fusers\u002F{id}\", getUser) \u002F\u002F 405 on wrong method, 404 on no match\nid := r.PathValue(\"id\")                    \u002F\u002F inside the handler\n\ntype apiHandler func(http.ResponseWriter, *http.Request) error\nfunc (h apiHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tif err := h(w, r); err != nil { \u002F* classify via errors.Is\u002FAs -> status + slog *\u002F }\n}\n```\n\nSet **all four** `http.Server` timeouts (`ReadHeaderTimeout`, `ReadTimeout`, `WriteTimeout`,\n`IdleTimeout`) — an unbounded read is a Slowloris DoS. Graceful shutdown on signal:\n`signal.NotifyContext(ctx, os.Interrupt, syscall.SIGTERM)`, then `srv.Shutdown(shutdownCtx)`\non `\u003C-ctx.Done()`.\n\nRouting patterns, chi vs stdlib, the full middleware chain (request-id, slog, panic-recovery,\ntimeout), config, timeout values, functional-options server, and JSON helpers ->\n`references\u002Fhttp-services.md`.\n\n## Project layout\n\n```text\ncmd\u002Fapi\u002Fmain.go        # entrypoint: wiring only\ninternal\u002Fhandler\u002F      # HTTP adapters\ninternal\u002Fservice\u002F      # business logic; defines the interfaces it needs\ninternal\u002Frepository\u002F   # data access (pgx); implements service interfaces\ninternal\u002Fconfig\u002F       # env parsing, validation\npkg\u002F                   # ONLY genuinely reusable, stable public API\ntestdata\u002F              # fixtures, golden files\ngo.mod go.sum\n```\n\nWire the layers with **constructor injection**, outermost depends inward:\n`repo := repository.New(db); svc := service.New(repo); h := handler.New(svc)`.\n\nPackage naming: short, lowercase, no underscores, no `util`\u002F`common`, avoid stutter\n(`user.User`, not `user.UserStruct`). Interfaces live on the **consumer side**: the\n`service` package declares `UserStore`; the `repository` package implements it without\nimporting the interface.\n\n## Testing (essentials)\n\nTable-driven with subtests and parallelism:\n\n```go\nfunc TestParse(t *testing.T) {\n\ttests := []struct {\n\t\tname    string\n\t\tin      string\n\t\twantErr error\n\t}{\n\t\t{\"ok\", \"42\", nil},\n\t\t{\"bad\", \"x\", ErrInvalid},\n\t}\n\tfor _, tt := range tests { \u002F\u002F Go 1.22+: no tt := tt needed\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tt.Parallel()\n\t\t\t_, err := Parse(tt.in)\n\t\t\tif !errors.Is(err, tt.wantErr) { \u002F\u002F classify, not just != nil\n\t\t\t\tt.Fatalf(\"got %v, want %v\", err, tt.wantErr)\n\t\t\t}\n\t\t})\n\t}\n}\n```\n\nHTTP handlers via `httptest`: `req := httptest.NewRequest(\"GET\", \"\u002Fusers\u002F1\", nil)`;\n`w := httptest.NewRecorder()`; `h.ServeHTTP(w, req)`; then assert on `w.Code` \u002F `w.Body`.\n\nUse `t.Helper()` in assertions, `t.TempDir()` for files, `t.Cleanup()` for teardown,\n`t.Setenv()` for env. Run `go test -race -cover .\u002F...`, and treat `go vet` \u002F `staticcheck`\nfailures as build failures. Stdlib `testing` is the default; reach for `testify\u002Frequire` only\nfor deep-equality or large suites.\n\nGolden files, fuzzing, benchmarks, httptest matrices, interface fakes ->\n`references\u002Ftesting.md`.\n\n## Security (embedded)\n\nValidate at the boundary: parametrize SQL (PostgreSQL; prefer `pgx v5` over `database\u002Fsql`);\ncap request bodies and reject unknown fields; set a TLS floor and trust the `crypto\u002Ftls`\ndefaults:\n\n```go\n\u002F\u002F Good                                       \u002F\u002F Bad: string interpolation = SQL injection.\ndb.QueryContext(ctx, \"... WHERE id = $1\", id) \u002F\u002F db.QueryContext(ctx, fmt.Sprintf(\"... '%s'\", id))\n\nr.Body = http.MaxBytesReader(w, r.Body, 1\u003C\u003C20) \u002F\u002F 1 MiB cap\ndec := json.NewDecoder(r.Body)\ndec.DisallowUnknownFields()\n\ntlsCfg := &tls.Config{MinVersion: tls.VersionTLS12} \u002F\u002F do not hand-pick cipher suites\n```\n\n**Server timeouts** are a DoS control - set all four (see HTTP services above).\n\nRun `govulncheck .\u002F...` in CI; keep deps honest with `go mod tidy` + `go mod verify`. Read\nsecrets from env \u002F a secret manager, never log them; redact tokens with slog `ReplaceAttr`.\nDeeper authz\u002Fabuse review -> `secure-coding`.\n\n## Production\n\nWire `log\u002Fslog` JSON in `main` (level from env), then `slog.SetDefault`:\n\n```go\nlogger := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: lvl}))\nslog.SetDefault(logger)\n```\n\nStamp the version with `ldflags` and read module info at runtime:\n\n```bash\ngo build -ldflags \"-X main.version=$(git describe --tags --always)\" .\u002Fcmd\u002Fapi\n# at runtime: if info, ok := debug.ReadBuildInfo(); ok { slog.Info(\"build\", \"go\", info.GoVersion) }\n```\n\nMount `net\u002Fhttp\u002Fpprof` on a **separate internal** mux\u002Fport (never the public listener);\nexpose `\u002Fhealthz` (static 200 liveness) and `\u002Freadyz` (calls `db.PingContext` with a short\ntimeout, 503 on failure). Graceful shutdown as shown above.\n\nDocker note: distroless\u002Fstatic base, `CGO_ENABLED=0`, multi-stage build. Full Containerfile\n-> `deployment`.\n\n## Anti-patterns\n\n| Anti-pattern | Do instead |\n| --- | --- |\n| Storing `ctx` in a struct to avoid threading it | `ctx` is the first arg of every call. |\n| `_ = err` because it \"can't fail\" | Handle, log, or document why; `errcheck` catches it. |\n| String-comparing the error message | `errors.Is` \u002F `errors.As`; messages are not API. |\n| Global `db` \u002F `logger` because it's \"simpler\" | Inject via constructor; globals kill testability. |\n| Fire-and-forget goroutine (\"it'll finish\") | Unbounded\u002Funstoppable goroutine = leak; give it ctx + buffer. |\n| `tt := tt` added \"to be safe\" | Go 1.22 fixed loopvar; it's noise now. |\n| Interface in the provider package, returning the interface | Return structs; interface lives with the consumer. |\n| No timeouts because \"the LB handles it\" | Set all four `http.Server` timeouts; Slowloris is real. |\n| `panic` on bad input | Return an error; panic only for programmer bugs \u002F `main` wiring. |\n| Skipping `-race` because tests pass | Race bugs are silent; `-race` in CI is mandatory. |\n| `fmt.Sprintf` into SQL on \"trusted\" input | Parametrize (`$1`...); trust nothing at the boundary. |\n| `testify` everywhere | Stdlib first; reach for testify only when it earns its weight. |\n\n## Toolchain gate\n\n| Task | Command |\n| --- | --- |\n| Format | `gofmt -w .` \u002F `goimports -w .` |\n| Vet | `go vet .\u002F...` |\n| Lint | `staticcheck .\u002F...` \u002F `golangci-lint run` |\n| Test (race+cover) | `go test -race -cover .\u002F...` |\n| Fuzz | `go test -fuzz=Fuzz -fuzztime=30s` |\n| Vulns | `govulncheck .\u002F...` |\n| Local gate | `.\u002Fscripts\u002Fverify.sh` (run in your module root) |\n\n## Project grounding (02-DOCS)\n\nIn a project with a `02-DOCS\u002F` layer (the [`harness`](..\u002Fharness\u002FSKILL.md) Karpathy wiki), this\nproject's service decisions live in `02-DOCS\u002Fwiki\u002Fstack\u002Fgo.md`, indexed from\n`02-DOCS\u002Fwiki\u002Findex.md` (the Knowledge map; root `CLAUDE.md` keeps only a short pointer to it).\nRead it first on every use and stay consistent. If it is missing or stale, write the project's\nreal choices there — the project layout, the router (stdlib 1.22 \u002F chi), the error and `slog`\nconventions, concurrency\u002Ftimeout defaults — index it, and bump its `Updated` date in the same\nchange.\n\nNo `02-DOCS\u002F` layer? Skip silently (optionally suggest `harness`). Unlike the brand study,\ntechnical conventions are *recorded, not gated* — never block the task on this.\n","# Idiomatic Go services\n\nTargets **Go 1.22+** (Go 1.26 is the current stable release): enhanced `net\u002Fhttp` routing\n(`mux.HandleFunc(\"GET \u002Fusers\u002F{id}\", h)` + `r.PathValue`), `log\u002Fslog` structured\nlogging, and fixed loop-variable semantics (no more `tt := tt`).\n\n> **⚠️ SDD new-feature gate — read this first.** If this skill fired on a **new, non-trivial feature or behaviour change** and there is **no approved spec + plan** under `02-DOCS\u002Fwiki\u002Fsdd\u002F`, STOP — do **not** write feature code yet. Hand off to `..\u002Fspecify\u002FSKILL.md` first: it runs brainstorm → spec → plan → tasks before any code, then routes back here once the plan is approved. Build here directly only for a genuinely one-line \u002F low-risk change. Method: `..\u002Fsdd\u002FSKILL.md`.\n\n## Boundary\n\nGo error handling and HTTP contract design (status-code taxonomy, REST resource naming) live\n**here** — this skill is the canonical authority for both in Go. Delegate outward:\n\n- Language-agnostic abuse\u002Fauthz review, threat modeling, OWASP-class bugs ->\n  [`secure-coding`](..\u002Fsecure-coding\u002FSKILL.md). This skill keeps the Go-specific controls:\n  SQL params, server timeouts, `govulncheck`, TLS defaults.\n- Containerfile \u002F k8s \u002F CI pipeline authoring -> [`deployment`](..\u002Fdeployment\u002FSKILL.md).\n  This skill ships only a Docker note + `ldflags`.\n- Recording per-project conventions in a workspace wiki -> [`harness`](..\u002Fharness\u002FSKILL.md)\n  (see \"Project grounding\" below).\n\nNon-service Go (CLI tooling, codegen, ML): the patterns apply, but the HTTP\u002Fproduction half\nis irrelevant.\n\n## Idioms\n\n**Useful zero value.** Design types so the zero value works before any constructor.\n\n```go\n\u002F\u002F Good: zero-value Counter is ready; the zero-value mutex is unlocked. var b bytes.Buffer too.\ntype Counter struct {\n\tmu sync.Mutex\n\tn  int\n}\n\nfunc (c *Counter) Inc() { c.mu.Lock(); c.n++; c.mu.Unlock() }\n\n\u002F\u002F Bad: nil map field panics on first write (assignment to entry in nil map); hidden init step.\ntype Registry struct{ items map[string]int }\n\nfunc (r *Registry) Add(k string) { r.items[k]++ } \u002F\u002F panic if items was never make()'d\n```\n\n**Accept interfaces, return structs.** Return the concrete type; declare the interface\nwhere it is consumed.\n\n```go\ntype UserStore interface { \u002F\u002F declared in package service - only what it needs\n\tGetUser(ctx context.Context, id string) (*User, error)\n}\nfunc NewService(s UserStore) *Service { return &Service{store: s} } \u002F\u002F Good: return *Service\n\u002F\u002F Bad: func NewService(s UserStore) UserStore - returning the interface hides the type.\n```\n\n**Functional options.** Defaults first, then apply options.\n\n```go\ntype Server struct {\n\taddr    string\n\ttimeout time.Duration\n\tlogger  *slog.Logger\n}\ntype Option func(*Server)\n\nfunc WithTimeout(d time.Duration) Option { return func(s *Server) { s.timeout = d } }\nfunc WithLogger(l *slog.Logger) Option   { return func(s *Server) { s.logger = l } }\n\nfunc NewServer(addr string, opts ...Option) *Server {\n\ts := &Server{addr: addr, timeout: 30 * time.Second, logger: slog.Default()} \u002F\u002F defaults first\n\tfor _, opt := range opts {\n\t\topt(s)\n\t}\n\treturn s\n}\n```\n\nUse a plain `Config` struct once options exceed ~5; options are for optional, composable\ntuning, not required fields.\n\n**Embedding for composition.** Embed to borrow a behavior, not to fake inheritance.\n\n```go\n\u002F\u002F Good: the service gets .Info\u002F.Error for free from the embedded logger.\ntype Service struct {\n\t*slog.Logger\n\tstore UserStore\n}\n\u002F\u002F Bad: deep type trees (Base -> Middle -> Leaf) modeling \"is-a\" inheritance - avoid.\n```\n\n**Early return.** Clear over clever: invert the error and `return`; keep the happy path flat\n(no arrow code).\n\n```go\n\u002F\u002F Good: each failure returns immediately; the success path is unindented.\nfunc save(ctx context.Context, u *User) error {\n\tif u == nil {\n\t\treturn errors.New(\"nil user\")\n\t}\n\tif err := validate(u); err != nil {\n\t\treturn fmt.Errorf(\"validate: %w\", err)\n\t}\n\treturn store.Put(ctx, u)\n}\n\u002F\u002F Bad: if u != nil { if err := validate(u); err == nil { ... } else { ... } } - arrow code.\n```\n\n**No package-level mutable state.** Inject via constructor (`func New(db *sql.DB) *Server`),\nnever a global `var db *sql.DB` opened in `init()` - globals couple everything and kill\ntestability.\n\n**Receivers.** Pick value or pointer per type and stay consistent across its method set;\nmutating \u002F large \u002F contains-`sync` -> pointer.\n\n**Go 1.22 loopvar.** Loop variables are per-iteration now. Stop emitting the workaround:\ninside `for _, tt := range tests` the line `\u002F\u002F tt := tt` is obsolete - DELETE it.\n\n## Errors\n\n**Sentinel vs typed.** Sentinels for identity; typed errors for data.\n\n```go\nvar ErrNotFound = errors.New(\"not found\")         \u002F\u002F sentinel: identity\ntype ValidationError struct{ Field, Msg string }  \u002F\u002F typed: carries data\nfunc (e *ValidationError) Error() string { return fmt.Sprintf(\"%s: %s\", e.Field, e.Msg) }\n```\n\n**Wrap and classify.** Wrap every crossed boundary with `%w`; never compare message strings.\n\n```go\nerr := fmt.Errorf(\"find user %s: %w\", id, ErrNotFound)\nif errors.Is(err, ErrNotFound) { \u002F* sentinel match through the wrap chain *\u002F }\nvar verr *ValidationError\nif errors.As(err, &verr) { \u002F* typed match: verr.Field, verr.Msg *\u002F }\njoined := errors.Join(err1, err2) \u002F\u002F 1.20+: aggregate; Is\u002FAs traverse both\n```\n\n**3-layer boundary (the canonical flow).** Repo wraps the driver sentinel into a domain\nsentinel; service passes it through; handler classifies once and maps to a status, logging\nonly the unexpected.\n\n```go\n\u002F\u002F repository: translate sql.ErrNoRows into a domain sentinel, keep the chain.\nfunc (r *Repo) GetUser(ctx context.Context, id string) (*User, error) {\n\tvar u User\n\terr := r.db.QueryRowContext(ctx, \"SELECT id, name FROM users WHERE id = $1\", id).\n\t\tScan(&u.ID, &u.Name)\n\tif errors.Is(err, sql.ErrNoRows) {\n\t\treturn nil, fmt.Errorf(\"user %s: %w\", id, ErrNotFound)\n\t}\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"query user %s: %w\", id, err)\n\t}\n\treturn &u, nil\n}\n\n\u002F\u002F handler: classify once, map to HTTP status.\nfunc (h *Handler) getUser(w http.ResponseWriter, r *http.Request) {\n\tu, err := h.svc.GetUser(r.Context(), r.PathValue(\"id\"))\n\tswitch {\n\tcase err == nil:\n\t\twriteJSON(w, http.StatusOK, u)\n\tcase errors.Is(err, ErrNotFound):\n\t\thttp.Error(w, \"not found\", http.StatusNotFound)\n\tdefault:\n\t\tslog.Error(\"get user\", \"err\", err)\n\t\thttp.Error(w, \"internal error\", http.StatusInternalServerError)\n\t}\n}\n```\n\nFull handler adapter (error-returning `apiHandler`) -> `references\u002Fhttp-services.md`.\n\n**`defer` + named return** to capture `Close()` errors:\n\n```go\nfunc read(name string) (err error) {\n\tf, e := os.Open(name)\n\tif e != nil {\n\t\treturn e\n\t}\n\tdefer func() { err = errors.Join(err, f.Close()) }() \u002F\u002F capture Close() into the return\n\treturn nil\n}\n```\n\n## Concurrency (essentials)\n\n`context.Context` is the **first** param of every call, never stored in a struct, never `nil`\n(use `context.TODO()` while wiring). Bound work with a context deadline; bound concurrency\nwith `errgroup` — the derived `ctx` cancels siblings on first error, and `g.SetLimit(n)` caps\nin-flight goroutines:\n\n```go\ng, ctx := errgroup.WithContext(ctx)\ng.SetLimit(8)\nfor _, id := range ids {\n\tg.Go(func() error { return process(ctx, id) }) \u002F\u002F Go 1.22+: no id := id needed\n}\nerr := g.Wait()\n```\n\nThree rules cover most service code: every goroutine needs a known exit path (a started\ngoroutine you cannot stop is a leak); an unbuffered `ch \u003C- v` with no receiver after a cancel\nblocks forever, so buffer it and `select` on `ctx.Done()`; **run `-race` in CI**. Low-level\nneeds map to `sync.Once` (lazy init), `sync.RWMutex` (read-heavy state), `sync\u002Fatomic`\n(`atomic.Int64` counters).\n\nFull implementations — context plumbing, channel\u002Fselect patterns, leak detection, worker\npools, pipelines, fan-in\u002Fout, semaphores, `singleflight`, and a `withRetry` helper (backoff +\nfull jitter, `ctx`-aware, **never retries 4xx**) -> `references\u002Fconcurrency.md`.\n\n## HTTP services (essentials)\n\nGo 1.22 routed mux — method and path live in the pattern; the `error`-returning adapter\ncentralizes status mapping:\n\n```go\nmux := http.NewServeMux()\nmux.HandleFunc(\"GET \u002Fusers\u002F{id}\", getUser) \u002F\u002F 405 on wrong method, 404 on no match\nid := r.PathValue(\"id\")                    \u002F\u002F inside the handler\n\ntype apiHandler func(http.ResponseWriter, *http.Request) error\nfunc (h apiHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tif err := h(w, r); err != nil { \u002F* classify via errors.Is\u002FAs -> status + slog *\u002F }\n}\n```\n\nSet **all four** `http.Server` timeouts (`ReadHeaderTimeout`, `ReadTimeout`, `WriteTimeout`,\n`IdleTimeout`) — an unbounded read is a Slowloris DoS. Graceful shutdown on signal:\n`signal.NotifyContext(ctx, os.Interrupt, syscall.SIGTERM)`, then `srv.Shutdown(shutdownCtx)`\non `\u003C-ctx.Done()`.\n\nRouting patterns, chi vs stdlib, the full middleware chain (request-id, slog, panic-recovery,\ntimeout), config, timeout values, functional-options server, and JSON helpers ->\n`references\u002Fhttp-services.md`.\n\n## Project layout\n\n```text\ncmd\u002Fapi\u002Fmain.go        # entrypoint: wiring only\ninternal\u002Fhandler\u002F      # HTTP adapters\ninternal\u002Fservice\u002F      # business logic; defines the interfaces it needs\ninternal\u002Frepository\u002F   # data access (pgx); implements service interfaces\ninternal\u002Fconfig\u002F       # env parsing, validation\npkg\u002F                   # ONLY genuinely reusable, stable public API\ntestdata\u002F              # fixtures, golden files\ngo.mod go.sum\n```\n\nWire the layers with **constructor injection**, outermost depends inward:\n`repo := repository.New(db); svc := service.New(repo); h := handler.New(svc)`.\n\nPackage naming: short, lowercase, no underscores, no `util`\u002F`common`, avoid stutter\n(`user.User`, not `user.UserStruct`). Interfaces live on the **consumer side**: the\n`service` package declares `UserStore`; the `repository` package implements it without\nimporting the interface.\n\n## Testing (essentials)\n\nTable-driven with subtests and parallelism:\n\n```go\nfunc TestParse(t *testing.T) {\n\ttests := []struct {\n\t\tname    string\n\t\tin      string\n\t\twantErr error\n\t}{\n\t\t{\"ok\", \"42\", nil},\n\t\t{\"bad\", \"x\", ErrInvalid},\n\t}\n\tfor _, tt := range tests { \u002F\u002F Go 1.22+: no tt := tt needed\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tt.Parallel()\n\t\t\t_, err := Parse(tt.in)\n\t\t\tif !errors.Is(err, tt.wantErr) { \u002F\u002F classify, not just != nil\n\t\t\t\tt.Fatalf(\"got %v, want %v\", err, tt.wantErr)\n\t\t\t}\n\t\t})\n\t}\n}\n```\n\nHTTP handlers via `httptest`: `req := httptest.NewRequest(\"GET\", \"\u002Fusers\u002F1\", nil)`;\n`w := httptest.NewRecorder()`; `h.ServeHTTP(w, req)`; then assert on `w.Code` \u002F `w.Body`.\n\nUse `t.Helper()` in assertions, `t.TempDir()` for files, `t.Cleanup()` for teardown,\n`t.Setenv()` for env. Run `go test -race -cover .\u002F...`, and treat `go vet` \u002F `staticcheck`\nfailures as build failures. Stdlib `testing` is the default; reach for `testify\u002Frequire` only\nfor deep-equality or large suites.\n\nGolden files, fuzzing, benchmarks, httptest matrices, interface fakes ->\n`references\u002Ftesting.md`.\n\n## Security (embedded)\n\nValidate at the boundary: parametrize SQL (PostgreSQL; prefer `pgx v5` over `database\u002Fsql`);\ncap request bodies and reject unknown fields; set a TLS floor and trust the `crypto\u002Ftls`\ndefaults:\n\n```go\n\u002F\u002F Good                                       \u002F\u002F Bad: string interpolation = SQL injection.\ndb.QueryContext(ctx, \"... WHERE id = $1\", id) \u002F\u002F db.QueryContext(ctx, fmt.Sprintf(\"... '%s'\", id))\n\nr.Body = http.MaxBytesReader(w, r.Body, 1\u003C\u003C20) \u002F\u002F 1 MiB cap\ndec := json.NewDecoder(r.Body)\ndec.DisallowUnknownFields()\n\ntlsCfg := &tls.Config{MinVersion: tls.VersionTLS12} \u002F\u002F do not hand-pick cipher suites\n```\n\n**Server timeouts** are a DoS control - set all four (see HTTP services above).\n\nRun `govulncheck .\u002F...` in CI; keep deps honest with `go mod tidy` + `go mod verify`. Read\nsecrets from env \u002F a secret manager, never log them; redact tokens with slog `ReplaceAttr`.\nDeeper authz\u002Fabuse review -> `secure-coding`.\n\n## Production\n\nWire `log\u002Fslog` JSON in `main` (level from env), then `slog.SetDefault`:\n\n```go\nlogger := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: lvl}))\nslog.SetDefault(logger)\n```\n\nStamp the version with `ldflags` and read module info at runtime:\n\n```bash\ngo build -ldflags \"-X main.version=$(git describe --tags --always)\" .\u002Fcmd\u002Fapi\n# at runtime: if info, ok := debug.ReadBuildInfo(); ok { slog.Info(\"build\", \"go\", info.GoVersion) }\n```\n\nMount `net\u002Fhttp\u002Fpprof` on a **separate internal** mux\u002Fport (never the public listener);\nexpose `\u002Fhealthz` (static 200 liveness) and `\u002Freadyz` (calls `db.PingContext` with a short\ntimeout, 503 on failure). Graceful shutdown as shown above.\n\nDocker note: distroless\u002Fstatic base, `CGO_ENABLED=0`, multi-stage build. Full Containerfile\n-> `deployment`.\n\n## Anti-patterns\n\n| Anti-pattern | Do instead |\n| --- | --- |\n| Storing `ctx` in a struct to avoid threading it | `ctx` is the first arg of every call. |\n| `_ = err` because it \"can't fail\" | Handle, log, or document why; `errcheck` catches it. |\n| String-comparing the error message | `errors.Is` \u002F `errors.As`; messages are not API. |\n| Global `db` \u002F `logger` because it's \"simpler\" | Inject via constructor; globals kill testability. |\n| Fire-and-forget goroutine (\"it'll finish\") | Unbounded\u002Funstoppable goroutine = leak; give it ctx + buffer. |\n| `tt := tt` added \"to be safe\" | Go 1.22 fixed loopvar; it's noise now. |\n| Interface in the provider package, returning the interface | Return structs; interface lives with the consumer. |\n| No timeouts because \"the LB handles it\" | Set all four `http.Server` timeouts; Slowloris is real. |\n| `panic` on bad input | Return an error; panic only for programmer bugs \u002F `main` wiring. |\n| Skipping `-race` because tests pass | Race bugs are silent; `-race` in CI is mandatory. |\n| `fmt.Sprintf` into SQL on \"trusted\" input | Parametrize (`$1`...); trust nothing at the boundary. |\n| `testify` everywhere | Stdlib first; reach for testify only when it earns its weight. |\n\n## Toolchain gate\n\n| Task | Command |\n| --- | --- |\n| Format | `gofmt -w .` \u002F `goimports -w .` |\n| Vet | `go vet .\u002F...` |\n| Lint | `staticcheck .\u002F...` \u002F `golangci-lint run` |\n| Test (race+cover) | `go test -race -cover .\u002F...` |\n| Fuzz | `go test -fuzz=Fuzz -fuzztime=30s` |\n| Vulns | `govulncheck .\u002F...` |\n| Local gate | `.\u002Fscripts\u002Fverify.sh` (run in your module root) |\n\n## Project grounding (02-DOCS)\n\nIn a project with a `02-DOCS\u002F` layer (the [`harness`](..\u002Fharness\u002FSKILL.md) Karpathy wiki), this\nproject's service decisions live in `02-DOCS\u002Fwiki\u002Fstack\u002Fgo.md`, indexed from\n`02-DOCS\u002Fwiki\u002Findex.md` (the Knowledge map; root `CLAUDE.md` keeps only a short pointer to it).\nRead it first on every use and stay consistent. If it is missing or stale, write the project's\nreal choices there — the project layout, the router (stdlib 1.22 \u002F chi), the error and `slog`\nconventions, concurrency\u002Ftimeout defaults — index it, and bump its `Updated` date in the same\nchange.\n\nNo `02-DOCS\u002F` layer? Skip silently (optionally suggest `harness`). Unlike the brand study,\ntechnical conventions are *recorded, not gated* — never block the task on this.\n",{"name":5,"tags":24,"origin":29,"recommends":30,"description":7},[5,25,26,27,28],"golang","http","backend","service","risco",[31,32,33],"postgresdb","secure-coding","deployment","main","d69096e239f2a89aabc2cd078c47664a9d3b1e11","04-安全渗透\u002Fgo",3,"https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts","https:\u002F\u002Fgithub.com\u002Flza6","个人vx：Tf00798\r\n个人✈：@TFGY999","2026-10-08 14:29:22",{"source":8,"skillName":5,"commands":43,"prompt":53,"zipAvailable":54},[44,47,50],{"tool":45,"command":46},"npx","npx skills add lza6\u002FArmor-piercing-system-prompts --skill go",{"tool":48,"command":49},"bunx","bunx skills add lza6\u002FArmor-piercing-system-prompts --skill go",{"tool":51,"command":52},"pnpm","pnpm dlx skills add lza6\u002FArmor-piercing-system-prompts --skill go","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F04-安全渗透\u002Fgo\u002FSKILL.md",true,[56,62,66,70,74],{"path":57,"resourceType":58,"resourceTypeDesc":59,"sizeBytes":60,"sourceHtmlUrl":61},"evals\u002Fcases.yaml","REFERENCE","参考文档",5266,"https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F04-安全渗透\u002Fgo\u002Fevals\u002Fcases.yaml",{"path":63,"resourceType":58,"resourceTypeDesc":59,"sizeBytes":64,"sourceHtmlUrl":65},"evals\u002FREADME.md",2639,"https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F04-安全渗透\u002Fgo\u002Fevals\u002FREADME.md",{"path":67,"resourceType":58,"resourceTypeDesc":59,"sizeBytes":68,"sourceHtmlUrl":69},"references\u002Fconcurrency.md",16211,"https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F04-安全渗透\u002Fgo\u002Freferences\u002Fconcurrency.md",{"path":71,"resourceType":58,"resourceTypeDesc":59,"sizeBytes":72,"sourceHtmlUrl":73},"references\u002Fhttp-services.md",15019,"https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F04-安全渗透\u002Fgo\u002Freferences\u002Fhttp-services.md",{"path":75,"resourceType":58,"resourceTypeDesc":59,"sizeBytes":76,"sourceHtmlUrl":77},"references\u002Ftesting.md",10552,"https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F04-安全渗透\u002Fgo\u002Freferences\u002Ftesting.md",[79,87,92,99,106,113],{"skillNo":80,"name":81,"nameZh":6,"description":82,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":83,"categories":84,"keywords":85,"publishedAt":86},"01M7FFG485KY83TD6HSC4YPCMC","obsidian-clipper-template-creator","Guide for creating templates for the Obsidian Web Clipper. Use when you want to create a new clipping template, understand available variables, or format clipped content.","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fobsidian-clipper-template-creator\u002FSKILL.md",[],[],"2026-11-16 10:05:34",{"skillNo":88,"name":81,"nameZh":6,"description":82,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":89,"categories":90,"keywords":91,"publishedAt":86},"01M7FFG0T6AZ0STEJPSB3CX84K","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fobsidian-clipper-template-creator-antigravity-awesome-skills-main\u002FSKILL.md",[],[],{"skillNo":93,"name":94,"nameZh":6,"description":95,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":96,"categories":97,"keywords":98,"publishedAt":86},"01M7FFFY0QEM14SKWPDYGMXM2P","python-api","Programmatic Object-Detection-Metrics API guidance for BoundingBox, BoundingBoxes, Evaluator, enums, coordinate conversion, AP\u002FmAP semantics, and source-style import diagnostics.","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fobject-detection-metrics\u002Fsub-skills\u002Fpython-api\u002FSKILL.md",[],[],{"skillNo":100,"name":101,"nameZh":6,"description":102,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":103,"categories":104,"keywords":105,"publishedAt":86},"01M7FFFVZQZ2GJ0C0TGP7JHD20","file-evaluation","Folder-based PASCAL VOC AP\u002FmAP evaluation from ground-truth and detection text files.","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fobject-detection-metrics\u002Fsub-skills\u002Ffile-evaluation\u002FSKILL.md",[],[],{"skillNo":107,"name":108,"nameZh":6,"description":109,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":110,"categories":111,"keywords":112,"publishedAt":86},"01M7FFFSFNYSE77SJ6PE1CK2DA","object-detection-metrics","Guides legacy Object-Detection-Metrics PASCAL VOC AP\u002FmAP evaluation from detection text folders and direct Python API classes.","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fobject-detection-metrics\u002FSKILL.md",[],[],{"skillNo":114,"name":115,"nameZh":6,"description":116,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":117,"categories":118,"keywords":119,"publishedAt":86},"01M7FFFP0GCK1RVXBCPQ8APBMT","nx-workspace-patterns","Configure and optimize Nx monorepo workspaces. Use when setting up Nx, configuring project boundaries, optimizing build caching, or implementing affected commands.","https:\u002F\u002Fgithub.com\u002Flza6\u002FArmor-piercing-system-prompts\u002Fblob\u002Fmain\u002F07-后端与架构\u002Fnx-workspace-patterns\u002FSKILL.md",[],[]]