[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7B1G6R3C3XVGXVW6HH477QG":3,"skill-same:01M7B1G6R3C3XVGXVW6HH477QG":53},{"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":24,"commitSha":25,"skillDirectory":26,"forksCount":27,"repositoryHtmlUrl":28,"repositoryHomepageUrl":6,"ownerHtmlUrl":29,"ownerBlogUrl":30,"ownerDescription":31,"updatedAt":32,"install":33,"resources":46},"01M7B1G6R3C3XVGXVW6HH477QG","go",null,"Expert Go programming skill authored by spf13 (former Go team lead, author of Cobra, Viper, Hugo, Afero). Covers idiomatic Go — package design, error handling, interfaces, concurrency, testing, and project layout, current through Go 1.25. Use whenever Go code is written, reviewed, debugged, or refactored — any .go file, go.mod, CLI tool, or web service, and whenever the user mentions Go or golang, even if they don't ask for \"idiomatic\" code.","dhcgn\u002Fjxleet","dhcgn","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F6566207?v=4","01M79C8N70VH5NC77K0K15FS3N","Daniel","01M7B1ECRWDTH2W2ZH6B0F30BE",12,"MIT","https:\u002F\u002Fgithub.com\u002Fdhcgn\u002Fjxleet\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fgo\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: go\ndescription: >\n  Expert Go programming skill authored by spf13 (former Go team lead, author of Cobra, Viper, Hugo, Afero).\n  Covers idiomatic Go — package design, error handling, interfaces, concurrency, testing, and\n  project layout, current through Go 1.25. Use whenever Go code is written, reviewed, debugged, or\n  refactored — any .go file, go.mod, CLI tool, or web service, and whenever the user mentions\n  Go or golang, even if they don't ask for \"idiomatic\" code.\n---\n\n# Idiomatic Go: The Go Way\n\nIdiomatic Go patterns and best practices for building robust, efficient, and maintainable applications.\n\n## When to Activate\n\n- Writing new Go code\n- Reviewing or auditing existing Go code\n- Refactoring Go code (especially code that looks like Java\u002FSpring Boot patterns in Go)\n- Designing Go packages, modules, or APIs\n- Choosing between stdlib and third-party libraries\n- Any question about Go project structure, error handling, concurrency, or testing\n\n## Core Principles\n\n### 1. Clear is Better than Clever\n\nGo favors readability and simplicity over abstraction and cleverness. Code should be obvious. If you have to read a function three times to understand its control flow, it needs to be rewritten.\n\n```go\n\u002F\u002F Idiomatic: Direct, linear control flow. Note: no \"Get\" prefix — Go omits it.\nfunc LookupUser(id string) (*User, error) {\n    user, err := db.FindUser(id)\n    if err != nil {\n        return nil, fmt.Errorf(\"finding user %s: %w\", id, err)\n    }\n    return user, nil\n}\n```\n\n### 2. Make the Zero Value Useful\n\nDesign types so their zero value is immediately usable without initialization. This eliminates boilerplate constructors. `sync.Mutex` and `bytes.Buffer` are the gold standard for this.\n\n```go\n\u002F\u002F Idiomatic: Ready to use immediately\ntype Counter struct {\n    mu    sync.Mutex\n    count int\n}\n\nfunc (c *Counter) Inc() {\n    c.mu.Lock()\n    c.count++\n    c.mu.Unlock()\n}\n```\n\n### 3. Return Early, Keep the Happy Path Left\n\nHandle errors and edge cases immediately and return. Do not use `else` blocks for the main logic. The \"happy path\" of your function should never be indented.\n\n## Package Organization: Flat by Default\n\n**Anti-Pattern:** Using deeply nested directory trees or relying heavily on an `internal\u002F` folder by default to artificially enforce \"Clean Architecture\" layers. This leads to circular dependencies and difficult navigation.\n\n### 1. The Single-Package Default\n\nStart flat. If you are building a microservice or a simple tool, put everything in the root directory (or alongside your `main.go`). Only create a new package when you truly need a new namespace to clarify the code, or when you need to decouple a strictly independent domain.\n\n### 2. The Proper Use of `internal\u002F`\n\nThe `internal\u002F` directory has a specific compiler enforcement: it prevents other modules from importing the code inside it.\n\n- **For Applications:** If you are building an executable binary, nobody can import your code anyway. Using `internal\u002F` here is usually just adding unnecessary path depth.\n- **For Libraries:** Use `internal\u002F` sparingly. It should be reserved for complex subsystems where you need to share exported types between your own packages, but absolutely must prevent end-users from relying on those types.\n\n```\n\u002F\u002F Idiomatic: A flat, feature-focused library or simple app\nmyproject\u002F\n├── main.go           # Entry point (if application)\n├── server.go         # Core logic\n├── config.go         # Configuration\n├── parser.go         # Domain specific parsing\n├── parser_test.go\n├── go.mod\n└── go.sum\n```\n\n### 3. Domain Packages for Service Applications\n\nWhen an application has genuinely distinct, independently-testable domains, give each its own top-level package. The rule is still **one level deep** — no `internal\u002F` nesting, no Clean Architecture layers. Each package owns one concern. `main.go` wires them together.\n\nThe signal to create a package: can this domain be described in one sentence, and does it have no knowledge of the other packages? If yes, it earns its own package.\n\n```\n\u002F\u002F Idiomatic: A web service with distinct domain packages\nmyservice\u002F\n├── main.go        # wires everything together; no business logic here\n├── config\u002F        # Config struct, env loading\n├── auth\u002F          # identity verification, session middleware\n├── db\u002F            # data store client + all queries\n├── storage\u002F       # blob storage (S3, R2, GCS)\n├── billing\u002F       # payment provider + credit ledger\n├── jobs\u002F          # job lifecycle + queue dispatch + worker handler (same domain, one package)\n├── web\u002F           # HTTP handlers + HTML templates + static assets (tightly coupled by design)\n├── transcribe\u002F    # domain-specific processing — independent pure functions\n├── Makefile\n├── Dockerfile\n└── .env.example\n```\n\n**Rules for domain packages:**\n- Each package has **one clear purpose** — name it after what it does, not what layer it is (`jobs\u002F`, not `service\u002F`)\n- Packages do not import each other sideways — cycles are a sign of wrong boundaries; `main` is the wiring point\n- Related sub-concerns that always travel together stay in one package (e.g. job creation + worker handler both live in `jobs\u002F` because they share the job lifecycle domain)\n- HTTP handlers and the templates they render belong together in `web\u002F` — they are tightly coupled by design\n- Do not create `utils\u002F`, `helpers\u002F`, or `common\u002F` packages — these are symptoms of unclear ownership\n\n**Anti-pattern to reject:** Clean Architecture \u002F DDD layers (`service\u002F`, `repository\u002F`, `controller\u002F`, `domain\u002F`). These layer-named packages cause circular imports, force interface proliferation, and add zero clarity in Go. Domain-named packages (`auth\u002F`, `billing\u002F`, `jobs\u002F`) are the correct middle ground between \"too flat\" and \"over-engineered.\"\n\n## Interface Design\n\n### 1. Interfaces are Discovered, Not Designed Upfront\n\nWrite concrete types first. Only define an interface when you discover that multiple types need to be used interchangeably by a consumer.\n\n### 2. Define Interfaces Where They Are Used\n\nInterfaces belong in the package that *consumes* them, not the package that *implements* them. This decouples your packages.\n\n```go\n\u002F\u002F processor\u002Fprocessor.go\n\n\u002F\u002F Idiomatic: The consumer defines exactly what it needs.\n\u002F\u002F The concrete 'UserStore' doesn't even need to know this interface exists.\ntype UserFetcher interface {\n    FetchUser(id string) (*User, error)\n}\n\ntype Processor struct {\n    fetcher UserFetcher\n}\n```\n\n### 3. Accept Interfaces, Return Structs\n\nRequire the smallest interface possible as an input parameter (e.g., `io.Reader` instead of `*os.File`), but return a concrete struct so callers aren't forced to use type assertions to access specific fields or methods.\n\n## Library API Design\n\n### Domain Object as Entry Point\n\nWhen designing a Go library that wraps a stateful resource (a vault, a database connection, a config store), make that resource struct the primary object. Its methods return domain-typed sub-objects. **Avoid:**\n\n- Passing a config\u002Fresource struct as the first argument to every package-level function\n- Package-level global state (like pflag's default `FlagSet`) for library code that may be embedded\n\n**Do this instead:**\n\n```go\n\u002F\u002F Open the primary resource once\nv, err := vault.Open(path)\n\n\u002F\u002F Domain operations are methods on the primary object\n\u002F\u002F Each call is stateless (reloads fresh) — no cached state on the struct\nidx, err := v.People()             \u002F\u002F returns *people.Index, error\nnote, err := v.Daily(time.Now())   \u002F\u002F returns *daily.Note, error\nmtgs, err := v.Meetings()          \u002F\u002F returns *meetings.Index, error\n\n\u002F\u002F Domain types live in sub-packages — callers use type inference\np, err := idx.FindOne(\"Steve\")     \u002F\u002F *people.Person\n```\n\n**Why this pattern:**\n\n- The primary struct (`Vault`) is the single entry point — callers need just one import to get started\n- Sub-packages define the rich domain types (`people.Person`, `daily.Note`) — each type lives with the logic that owns it\n- No global state means the library is safe for concurrent use, multiple instances, and testing\n- Stateless method calls (reload fresh each time) keep the struct simple — no cache invalidation logic needed\n- Type inference (`:=`) means callers rarely need to explicitly import sub-packages for variable declarations\n\n**When to use a global instance instead:** Only for CLI-only tools (like `pflag` itself) where there is truly only ever one instance and ease of use for end-users outweighs library correctness.\n\n## Concurrency Patterns\n\n**Anti-Pattern:** Heavy, static Worker Pools. Go's scheduler is incredibly efficient; you don't need to manually manage pools of workers like OS threads in other languages.\n\n### 1. Share Memory by Communicating\n\nDon't use mutexes to protect shared data if you can pass that data over a channel instead. Channels orchestrate execution; mutexes serialize execution.\n\n### 2. Bounded Concurrency\n\nTo limit concurrency, use `errgroup` with `SetLimit`. Don't hand-roll a semaphore channel or a rigid worker pool when this exists.\n\n```go\nfunc FetchAll(ctx context.Context, urls []string, maxConcurrent int) error {\n    g, ctx := errgroup.WithContext(ctx)\n    g.SetLimit(maxConcurrent)\n\n    for _, url := range urls {\n        g.Go(func() error {\n            return fetch(ctx, url)\n        })\n    }\n\n    return g.Wait()\n}\n```\n\nLoop variables are per-iteration since Go 1.22 — never emit the old `url := url` capture line.\n\nWhen you don't need error propagation, `sync.WaitGroup.Go` (Go 1.25) removes the Add\u002FDone boilerplate:\n\n```go\nvar wg sync.WaitGroup\nfor _, url := range urls {\n    wg.Go(func() { process(url) })\n}\nwg.Wait()\n```\n\n### 3. Never Start a Goroutine Without Knowing How It Stops\n\nEvery `go func()` must have a clear exit condition, usually governed by a `context.Context` or a closed channel.\n\n## Configuration and Struct Design\n\n### Functional Options for Complex Initialization\n\nWhen a struct has many optional configuration parameters, avoid massive constructors. Use the Functional Options pattern.\n\n```go\ntype Server struct {\n    addr    string\n    timeout time.Duration\n}\n\ntype Option func(*Server)\n\nfunc WithTimeout(d time.Duration) Option {\n    return func(s *Server) { s.timeout = d }\n}\n\nfunc NewServer(addr string, opts ...Option) *Server {\n    s := &Server{\n        addr:    addr,\n        timeout: 30 * time.Second, \u002F\u002F Sane default\n    }\n    for _, opt := range opts {\n        opt(s)\n    }\n    return s\n}\n```\n\n## Error Handling\n\n### 1. Errors are Values\n\nErrors aren't exceptions to be caught; they are values to be handled. Check them explicitly.\n\n### 2. Wrap for Context, Not for Stack Traces\n\nWhen returning an error, add context about what you were trying to do.\n\n```go\n\u002F\u002F Idiomatic\ndata, err := os.ReadFile(path)\nif err != nil {\n    return fmt.Errorf(\"loading config file %s: %w\", path, err)\n}\n```\n\n## Testing Patterns\n\n**Anti-Pattern:** Relying on heavy BDD frameworks (like Ginkgo) or complex mocking generation tools. Go testing should just be Go programming.\n\n### 1. Table-Driven Tests\n\nThe absolute standard for unit testing in Go. Iterate over a slice of structs containing inputs and expected outputs using `t.Run()`.\n\n```go\nfunc TestParseConfig(t *testing.T) {\n    tests := []struct {\n        name    string\n        input   string\n        wantErr bool\n    }{\n        {\"valid config\", \"port=8080\", false},\n        {\"invalid format\", \"port=abc\", true},\n    }\n\n    for _, tt := range tests {\n        t.Run(tt.name, func(t *testing.T) {\n            _, err := ParseConfig(tt.input)\n            if (err != nil) != tt.wantErr {\n                t.Fatalf(\"ParseConfig() error = %v, wantErr %v\", err, tt.wantErr)\n            }\n        })\n    }\n}\n```\n\n### 2. Meaningful Helpers with `t.Helper()`\n\nWhen extracting repeated assertion logic, always call `t.Helper()` to ensure failures point to the actual test case, not the helper function line.\n\n### 3. Fakes and Stubs over Heavy Mocks\n\nLeverage Go's implicit interfaces to write simple, manual fakes. This keeps test dependencies lightweight and test logic transparent.\n\n### 4. Golden Files and the `testdata` Directory\n\nFor tests requiring complex inputs or producing large outputs, use a directory named `testdata`. The `go test` tool explicitly ignores these directories.\n\n### 5. Filesystem Abstraction (The Afero Pattern)\n\nDo not hardcode `os` package calls deep within business logic. Accept an interface for the filesystem so tests can run in memory without touching the disk. `github.com\u002Fspf13\u002Fafero` is the industry standard for this.\n\n```go\nimport \"github.com\u002Fspf13\u002Fafero\"\n\ntype FileProcessor struct {\n    fs afero.Fs\n}\n\nfunc NewFileProcessor(fs afero.Fs) *FileProcessor {\n    return &FileProcessor{fs: fs}\n}\n```\n\nIn tests, inject `afero.NewMemMapFs()` to completely eliminate disk I\u002FO and prevent flaky, slow tests.\n\n### 6. `cmp` over DeepEqual\n\nFor comparing complex structs or maps, use `github.com\u002Fgoogle\u002Fgo-cmp\u002Fcmp` for rich, readable diffs instead of the strict `reflect.DeepEqual`.\n\n### 7. Modern `testing` Additions (Go 1.24+)\n\n```go\n\u002F\u002F Test-scoped context — canceled automatically when the test ends.\n\u002F\u002F Use instead of context.Background() in tests.\nfunc TestFetch(t *testing.T) {\n    ctx := t.Context()\n    ...\n}\n\n\u002F\u002F Benchmarks: b.Loop() replaces the classic b.N loop — more accurate,\n\u002F\u002F prevents the compiler from optimizing the benchmarked call away.\nfunc BenchmarkParse(b *testing.B) {\n    for b.Loop() {\n        Parse(input)\n    }\n}\n\n\u002F\u002F t.Chdir(dir) changes working directory for the test and restores it after.\n```\n\n### 8. `testing\u002Fsynctest` for Concurrent Code (Go 1.25)\n\nTest goroutines and timeouts deterministically with a fake clock — no `time.Sleep` in tests, no flaky timing assumptions:\n\n```go\nfunc TestTimeout(t *testing.T) {\n    synctest.Test(t, func(t *testing.T) {\n        ctx, cancel := context.WithTimeout(t.Context(), time.Second)\n        defer cancel()\n        time.Sleep(2 * time.Second) \u002F\u002F instant — fake clock advances when all goroutines block\n        if ctx.Err() == nil {\n            t.Fatal(\"expected timeout\")\n        }\n    })\n}\n```\n\nNever write `time.Sleep(100 * time.Millisecond)` to \"wait for a goroutine\" in a test. Use synctest, channels, or explicit synchronization.\n\n## Generics (Go 1.18+)\n\nGenerics exist to eliminate duplicated algorithms, not to create type hierarchies. If you are thinking about generics in terms of inheritance or polymorphism, stop — you are writing Java.\n\n### When to Use Generics\n\nUse generics when you have the **same algorithm** that needs to operate on **multiple concrete types**:\n\n```go\n\u002F\u002F Good: generic algorithm, concrete types as inputs\nfunc Map[S, T any](slice []S, f func(S) T) []T {\n    result := make([]T, len(slice))\n    for i, v := range slice {\n        result[i] = f(v)\n    }\n    return result\n}\n\n\u002F\u002F Good: constraint expresses a meaningful requirement\nfunc Min[T cmp.Ordered](a, b T) T {\n    if a \u003C b {\n        return a\n    }\n    return b\n}\n```\n\n### When NOT to Use Generics\n\n```go\n\u002F\u002F Bad: generic interface for polymorphism — this is Java\ntype Repository[T any] interface {\n    Find(id string) (T, error)\n    Save(entity T) error\n}\n\n\u002F\u002F Good: a concrete interface for what you actually need\ntype UserStore interface {\n    FindUser(id string) (*User, error)\n    SaveUser(u *User) error\n}\n```\n\n- **Do not** create generic base types, generic services, or generic repositories.\n- **Do not** use `any` as a constraint to mean \"I don't know the type yet.\" That's a design smell.\n- **Do** use `comparable` when you need map keys or equality checks.\n- **Do** use `cmp.Ordered` when you need `\u003C`, `>`, `\u003C=`, `>=`.\n- Start with a concrete implementation. Generify only when you have the same logic repeated across 3+ types.\n- Generic type aliases are fully supported since Go 1.24.\n\n## Standard Library: Use the New Packages\n\nLLMs frequently suggest third-party utilities or write manual helpers that have been in the standard library since Go 1.21. **Always check stdlib first.**\n\n### `slices` package (Go 1.21)\n\n```go\nimport \"slices\"\n\n\u002F\u002F Searching and testing\nslices.Contains(s, \"value\")\nslices.Index(s, \"value\")           \u002F\u002F returns -1 if not found\nslices.ContainsFunc(s, func(v string) bool { return v == \"x\" })\n\n\u002F\u002F Sorting\nslices.Sort(s)                     \u002F\u002F sorts in place, works on any ordered type\nslices.SortFunc(s, func(a, b T) int { return cmp.Compare(a.Name, b.Name) })\nslices.IsSorted(s)\n\n\u002F\u002F Manipulation\nslices.Reverse(s)\nslices.Compact(s)                  \u002F\u002F removes consecutive duplicates\nslices.Delete(s, i, j)            \u002F\u002F removes elements [i, j)\nslices.Clone(s)                   \u002F\u002F shallow copy\nslices.Concat(s1, s2, s3)         \u002F\u002F concatenate multiple slices (1.22)\n\n\u002F\u002F Iterator bridging (1.23)\nslices.Collect(it)                \u002F\u002F iterator -> slice\nslices.Sorted(it)                 \u002F\u002F iterator -> sorted slice\nslices.Values(s)                  \u002F\u002F slice -> iterator\n```\n\nNever write `sort.Slice(s, func(i, j int) bool { return s[i] \u003C s[j] })` when `slices.Sort(s)` exists.\n\n### `maps` package (Go 1.21; iterators 1.23)\n\n```go\nimport \"maps\"\n\nmaps.Keys(m)        \u002F\u002F iterator over keys — collect with slices.Collect \u002F slices.Sorted\nmaps.Values(m)      \u002F\u002F iterator over values\nmaps.Clone(m)       \u002F\u002F shallow copy\nmaps.Copy(dst, src) \u002F\u002F copies all entries from src into dst\nmaps.DeleteFunc(m, func(k K, v V) bool { ... })  \u002F\u002F delete entries matching predicate\nmaps.Equal(m1, m2)  \u002F\u002F reports whether two maps are equal\n\n\u002F\u002F Common idiom: sorted keys in one line\nkeys := slices.Sorted(maps.Keys(m))\n```\n\n### `cmp` package (Go 1.21)\n\n```go\nimport \"cmp\"\n\ncmp.Compare(a, b)    \u002F\u002F returns -1, 0, or 1; works on any cmp.Ordered type\ncmp.Or(a, b, c)      \u002F\u002F returns first non-zero value — replaces ternary workarounds\nmin(a, b)            \u002F\u002F built-in since Go 1.21\nmax(a, b)            \u002F\u002F built-in since Go 1.21\n```\n\n`cmp.Or` is especially useful for default-value patterns:\n\n```go\n\u002F\u002F Instead of: if cfg.Timeout == 0 { cfg.Timeout = 30 * time.Second }\ncfg.Timeout = cmp.Or(cfg.Timeout, 30*time.Second)\n```\n\n### `errors.Join` (Go 1.20)\n\n```go\n\u002F\u002F Combine multiple errors — no third-party library needed\nerr := errors.Join(err1, err2, err3)\n\n\u002F\u002F Works correctly with errors.Is and errors.As\nif errors.Is(err, ErrNotFound) { ... }\n```\n\nUse this instead of `fmt.Errorf(\"%w; %w\", err1, err2)` or any `multierr` package.\n\n### Iterators: `iter` and Range-over-Func (Go 1.23)\n\nThe standard way to expose a sequence from an API without allocating a slice. Return `iter.Seq[T]` or `iter.Seq2[K, V]`; callers use plain `range`:\n\n```go\nfunc (idx *Index) All() iter.Seq[*Person] {\n    return func(yield func(*Person) bool) {\n        for _, p := range idx.people {\n            if !yield(p) {\n                return\n            }\n        }\n    }\n}\n\n\u002F\u002F Caller — just a normal range loop\nfor p := range idx.All() { ... }\n```\n\nPrefer returning iterators over slices for large or lazily-produced sequences. Don't invent a custom `Next()\u002FHasNext()` iterator type — that's Java.\n\n### `math\u002Frand\u002Fv2` (Go 1.22)\n\nAlways import `math\u002Frand\u002Fv2`, never the old `math\u002Frand`. Auto-seeded, cleaner API:\n\n```go\nimport \"math\u002Frand\u002Fv2\"\n\nrand.IntN(100)            \u002F\u002F was rand.Intn — note the capital N\nrand.N(10 * time.Second)  \u002F\u002F generic: random value in [0, n) for any integer type\n```\n\n### `encoding\u002Fjson`: `omitzero` (Go 1.24)\n\n`omitzero` omits any zero value — including `time.Time{}` and zero structs, which `omitempty` never handled correctly:\n\n```go\ntype Event struct {\n    Name      string    `json:\"name\"`\n    StartedAt time.Time `json:\"started_at,omitzero\"` \u002F\u002F omitempty would emit \"0001-01-01T...\"\n}\n```\n\n## Concurrency: Modern Patterns\n\n### `sync\u002Fatomic` Typed Values (Go 1.19)\n\nUse the typed atomic values instead of the function-based API:\n\n```go\n\u002F\u002F Old (still works but avoid for new code)\nvar count int64\natomic.AddInt64(&count, 1)\nval := atomic.LoadInt64(&count)\n\n\u002F\u002F New — type-safe, no pointer arithmetic\nvar count atomic.Int64\ncount.Add(1)\nval := count.Load()\n\n\u002F\u002F Other typed atomics\nvar flag  atomic.Bool\nvar ptr   atomic.Pointer[MyStruct]\nvar val32 atomic.Int32\nvar val64 atomic.Uint64\n```\n\n### `context.WithoutCancel` (Go 1.21)\n\nWhen you need to detach a context's cancellation but preserve its values (e.g., for a background task that should outlive a request):\n\n```go\n\u002F\u002F The background job should keep running even after the HTTP request context cancels\nbgCtx := context.WithoutCancel(requestCtx)\ngo doBackgroundWork(bgCtx)\n```\n\n## HTTP: Use the Improved stdlib Router (Go 1.22)\n\nLLMs reflexively recommend gorilla\u002Fmux or chi for any routing beyond the trivial. Since Go 1.22, the standard `net\u002Fhttp` ServeMux handles method and path-parameter routing natively.\n\n```go\nmux := http.NewServeMux()\n\n\u002F\u002F Method-scoped routes\nmux.HandleFunc(\"GET \u002Fusers\", listUsers)\nmux.HandleFunc(\"POST \u002Fusers\", createUser)\n\n\u002F\u002F Path parameters — accessed via r.PathValue\nmux.HandleFunc(\"GET \u002Fusers\u002F{id}\", func(w http.ResponseWriter, r *http.Request) {\n    id := r.PathValue(\"id\")\n    \u002F\u002F ...\n})\n\n\u002F\u002F Wildcard\nmux.HandleFunc(\"GET \u002Ffiles\u002F{path...}\", serveFile)\n```\n\nReach for chi or gorilla\u002Fmux only when you need named route generation or regex constraints — middleware doesn't justify a framework (see below). For pure method + path routing, the stdlib is sufficient.\n\n### Production Servers: Always Set Timeouts\n\n`http.ListenAndServe(addr, mux)` ships with **no timeouts** — a single slow client can hold a connection open forever (slow-loris). LLM-generated servers almost never set these. Never emit a production server without them:\n\n```go\nsrv := &http.Server{\n    Addr:              \":8080\",\n    Handler:           mux,\n    ReadHeaderTimeout: 5 * time.Second,   \u002F\u002F slow-loris protection\n    ReadTimeout:       10 * time.Second,  \u002F\u002F full request read\n    WriteTimeout:      30 * time.Second,  \u002F\u002F response write (covers handler time)\n    IdleTimeout:       120 * time.Second, \u002F\u002F keep-alive connections\n}\n```\n\nFor per-route control beyond `WriteTimeout`, use `http.TimeoutHandler` or handler-level `context.WithTimeout`. Outbound calls need the same discipline: `http.DefaultClient` has no timeout either — construct a client with one.\n\n### Graceful Shutdown\n\nEvery production server needs a shutdown path that stops accepting connections and drains in-flight requests. The pattern:\n\n```go\nfunc run(ctx context.Context) error {\n    ctx, stop := signal.NotifyContext(ctx, os.Interrupt, syscall.SIGTERM)\n    defer stop()\n\n    srv := &http.Server{ \u002F* ... timeouts as above ... *\u002F }\n\n    errCh := make(chan error, 1)\n    go func() { errCh \u003C- srv.ListenAndServe() }()\n\n    select {\n    case err := \u003C-errCh:\n        return err \u002F\u002F ListenAndServe failed at startup\n    case \u003C-ctx.Done():\n        shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)\n        defer cancel()\n        return srv.Shutdown(shutdownCtx) \u002F\u002F drain in-flight, then exit\n    }\n}\n```\n\n- `Shutdown` needs a fresh context with its own deadline — the signal context is already canceled.\n- Long-lived connections (SSE, websockets) must watch `r.Context()` or they'll hold shutdown until the drain deadline.\n\n### Middleware Is Just a Function\n\nNo framework needed. A middleware is `func(http.Handler) http.Handler`:\n\n```go\nfunc withRequestLog(logger *slog.Logger, next http.Handler) http.Handler {\n    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n        start := time.Now()\n        next.ServeHTTP(w, r)\n        logger.Info(\"request\", \"method\", r.Method, \"path\", r.URL.Path, \"dur\", time.Since(start))\n    })\n}\n\n\u002F\u002F Compose by wrapping — outermost runs first\nhandler := withRequestLog(logger, withAuth(mux))\n```\n\nDon't import a middleware framework for what function composition already does.\n\n## Syntax: Use Current Go\n\nLLMs frequently generate outdated syntax. Know the current idioms:\n\n### Range over Integer (Go 1.22)\n\n```go\n\u002F\u002F Old\nfor i := 0; i \u003C 10; i++ { ... }\n\n\u002F\u002F New\nfor i := range 10 { ... }\n```\n\n### Build Constraints\n\n```go\n\u002F\u002F Old (deprecated — do not generate)\n\u002F\u002F +build linux darwin\n\n\u002F\u002F Current\n\u002F\u002Fgo:build linux || darwin\n```\n\nThe `\u002F\u002Fgo:build` form is required since Go 1.17. Never emit the old `\u002F\u002F +build` syntax.\n\n### `any` Instead of `interface{}`\n\n```go\n\u002F\u002F Old\nfunc Print(v interface{}) { ... }\n\n\u002F\u002F Current — `any` is a built-in alias for interface{} since Go 1.18\nfunc Print(v any) { ... }\n```\n\n### Tool Dependencies in `go.mod` (Go 1.24)\n\nNever generate a `tools.go` file with blank imports. Track dev tools with the `tool` directive:\n\n```bash\ngo get -tool golang.org\u002Fx\u002Ftools\u002Fcmd\u002Fstringer\ngo tool stringer -type=Color   # run it\n```\n\n## Structured Logging with `log\u002Fslog` (Go 1.21)\n\nThe skill note above covers basic setup. The patterns LLMs most often get wrong:\n\n```go\n\u002F\u002F Pass a logger via context for request-scoped logging\nfunc HandleRequest(ctx context.Context, r *Request) {\n    logger := slog.With(\"request_id\", r.ID, \"user_id\", r.UserID)\n    \u002F\u002F All subsequent log calls carry these fields automatically\n    logger.Info(\"handling request\")\n    process(ctx, logger, r)\n}\n\n\u002F\u002F Group related fields\nlogger.With(slog.Group(\"http\",\n    slog.String(\"method\", r.Method),\n    slog.String(\"path\", r.URL.Path),\n    slog.Int(\"status\", status),\n))\n\n\u002F\u002F Log at the right level — LLMs over-use Info\nlogger.Debug(\"cache miss\", \"key\", key)     \u002F\u002F internal state, high volume\nlogger.Info(\"server started\", \"addr\", addr) \u002F\u002F lifecycle events\nlogger.Warn(\"retrying\", \"attempt\", n)       \u002F\u002F recoverable problems\nlogger.Error(\"request failed\", \"err\", err)  \u002F\u002F needs attention\n```\n\n- **Never** use a package-level `log` or `slog` global beyond `main`. Pass `*slog.Logger` as a dependency.\n- **Never** log and return an error. Log at the boundary, return the error through the call stack.\n- Use `slog.Default()` as the fallback only in `main` or in libraries when no logger is provided.\n\n## Debugging: The Go Toolchain Is Not the Problem\n\n**The Go tool is extremely reliable. It is almost never the source of a bug.**\n\nWhen debugging, do not waste time suspecting `go run`, `go build`, `go test`, or the build cache. The Go toolchain does what it says:\n\n- `go run` always recompiles from source. It does not use a stale cached binary.\n- `go build` is deterministic and correct.\n- `go test` runs the actual compiled test binary.\n- The build cache is keyed by source content — if the source changed, the cache is invalidated automatically.\n\n**If an error persists after you edit the code, the explanation is one of these — in order of likelihood:**\n\n1. The edit did not fix the underlying logic error.\n2. The edit was made in the wrong file, wrong function, or wrong package.\n3. There is a second call site with the same bug that was not updated.\n4. The error is coming from a different code path than the one being edited.\n\n**What to do instead of blaming the tool:**\n\n- Re-read the error message carefully. Go's error messages are accurate.\n- Confirm the file you edited is actually the file being compiled (`go list -f '{{.GoFiles}}' .`).\n- Add a `fmt.Println` or `t.Log` at the exact site to verify execution reaches it.\n- Check that all call sites of a changed function were updated.\n\nDo not suggest clearing the build cache (`go clean -cache`), restarting the Go toolchain, or any other tool-level intervention before first exhausting all code-level explanations. The tool is not lying to you.","# Idiomatic Go: The Go Way\n\nIdiomatic Go patterns and best practices for building robust, efficient, and maintainable applications.\n\n## When to Activate\n\n- Writing new Go code\n- Reviewing or auditing existing Go code\n- Refactoring Go code (especially code that looks like Java\u002FSpring Boot patterns in Go)\n- Designing Go packages, modules, or APIs\n- Choosing between stdlib and third-party libraries\n- Any question about Go project structure, error handling, concurrency, or testing\n\n## Core Principles\n\n### 1. Clear is Better than Clever\n\nGo favors readability and simplicity over abstraction and cleverness. Code should be obvious. If you have to read a function three times to understand its control flow, it needs to be rewritten.\n\n```go\n\u002F\u002F Idiomatic: Direct, linear control flow. Note: no \"Get\" prefix — Go omits it.\nfunc LookupUser(id string) (*User, error) {\n    user, err := db.FindUser(id)\n    if err != nil {\n        return nil, fmt.Errorf(\"finding user %s: %w\", id, err)\n    }\n    return user, nil\n}\n```\n\n### 2. Make the Zero Value Useful\n\nDesign types so their zero value is immediately usable without initialization. This eliminates boilerplate constructors. `sync.Mutex` and `bytes.Buffer` are the gold standard for this.\n\n```go\n\u002F\u002F Idiomatic: Ready to use immediately\ntype Counter struct {\n    mu    sync.Mutex\n    count int\n}\n\nfunc (c *Counter) Inc() {\n    c.mu.Lock()\n    c.count++\n    c.mu.Unlock()\n}\n```\n\n### 3. Return Early, Keep the Happy Path Left\n\nHandle errors and edge cases immediately and return. Do not use `else` blocks for the main logic. The \"happy path\" of your function should never be indented.\n\n## Package Organization: Flat by Default\n\n**Anti-Pattern:** Using deeply nested directory trees or relying heavily on an `internal\u002F` folder by default to artificially enforce \"Clean Architecture\" layers. This leads to circular dependencies and difficult navigation.\n\n### 1. The Single-Package Default\n\nStart flat. If you are building a microservice or a simple tool, put everything in the root directory (or alongside your `main.go`). Only create a new package when you truly need a new namespace to clarify the code, or when you need to decouple a strictly independent domain.\n\n### 2. The Proper Use of `internal\u002F`\n\nThe `internal\u002F` directory has a specific compiler enforcement: it prevents other modules from importing the code inside it.\n\n- **For Applications:** If you are building an executable binary, nobody can import your code anyway. Using `internal\u002F` here is usually just adding unnecessary path depth.\n- **For Libraries:** Use `internal\u002F` sparingly. It should be reserved for complex subsystems where you need to share exported types between your own packages, but absolutely must prevent end-users from relying on those types.\n\n```\n\u002F\u002F Idiomatic: A flat, feature-focused library or simple app\nmyproject\u002F\n├── main.go           # Entry point (if application)\n├── server.go         # Core logic\n├── config.go         # Configuration\n├── parser.go         # Domain specific parsing\n├── parser_test.go\n├── go.mod\n└── go.sum\n```\n\n### 3. Domain Packages for Service Applications\n\nWhen an application has genuinely distinct, independently-testable domains, give each its own top-level package. The rule is still **one level deep** — no `internal\u002F` nesting, no Clean Architecture layers. Each package owns one concern. `main.go` wires them together.\n\nThe signal to create a package: can this domain be described in one sentence, and does it have no knowledge of the other packages? If yes, it earns its own package.\n\n```\n\u002F\u002F Idiomatic: A web service with distinct domain packages\nmyservice\u002F\n├── main.go        # wires everything together; no business logic here\n├── config\u002F        # Config struct, env loading\n├── auth\u002F          # identity verification, session middleware\n├── db\u002F            # data store client + all queries\n├── storage\u002F       # blob storage (S3, R2, GCS)\n├── billing\u002F       # payment provider + credit ledger\n├── jobs\u002F          # job lifecycle + queue dispatch + worker handler (same domain, one package)\n├── web\u002F           # HTTP handlers + HTML templates + static assets (tightly coupled by design)\n├── transcribe\u002F    # domain-specific processing — independent pure functions\n├── Makefile\n├── Dockerfile\n└── .env.example\n```\n\n**Rules for domain packages:**\n- Each package has **one clear purpose** — name it after what it does, not what layer it is (`jobs\u002F`, not `service\u002F`)\n- Packages do not import each other sideways — cycles are a sign of wrong boundaries; `main` is the wiring point\n- Related sub-concerns that always travel together stay in one package (e.g. job creation + worker handler both live in `jobs\u002F` because they share the job lifecycle domain)\n- HTTP handlers and the templates they render belong together in `web\u002F` — they are tightly coupled by design\n- Do not create `utils\u002F`, `helpers\u002F`, or `common\u002F` packages — these are symptoms of unclear ownership\n\n**Anti-pattern to reject:** Clean Architecture \u002F DDD layers (`service\u002F`, `repository\u002F`, `controller\u002F`, `domain\u002F`). These layer-named packages cause circular imports, force interface proliferation, and add zero clarity in Go. Domain-named packages (`auth\u002F`, `billing\u002F`, `jobs\u002F`) are the correct middle ground between \"too flat\" and \"over-engineered.\"\n\n## Interface Design\n\n### 1. Interfaces are Discovered, Not Designed Upfront\n\nWrite concrete types first. Only define an interface when you discover that multiple types need to be used interchangeably by a consumer.\n\n### 2. Define Interfaces Where They Are Used\n\nInterfaces belong in the package that *consumes* them, not the package that *implements* them. This decouples your packages.\n\n```go\n\u002F\u002F processor\u002Fprocessor.go\n\n\u002F\u002F Idiomatic: The consumer defines exactly what it needs.\n\u002F\u002F The concrete 'UserStore' doesn't even need to know this interface exists.\ntype UserFetcher interface {\n    FetchUser(id string) (*User, error)\n}\n\ntype Processor struct {\n    fetcher UserFetcher\n}\n```\n\n### 3. Accept Interfaces, Return Structs\n\nRequire the smallest interface possible as an input parameter (e.g., `io.Reader` instead of `*os.File`), but return a concrete struct so callers aren't forced to use type assertions to access specific fields or methods.\n\n## Library API Design\n\n### Domain Object as Entry Point\n\nWhen designing a Go library that wraps a stateful resource (a vault, a database connection, a config store), make that resource struct the primary object. Its methods return domain-typed sub-objects. **Avoid:**\n\n- Passing a config\u002Fresource struct as the first argument to every package-level function\n- Package-level global state (like pflag's default `FlagSet`) for library code that may be embedded\n\n**Do this instead:**\n\n```go\n\u002F\u002F Open the primary resource once\nv, err := vault.Open(path)\n\n\u002F\u002F Domain operations are methods on the primary object\n\u002F\u002F Each call is stateless (reloads fresh) — no cached state on the struct\nidx, err := v.People()             \u002F\u002F returns *people.Index, error\nnote, err := v.Daily(time.Now())   \u002F\u002F returns *daily.Note, error\nmtgs, err := v.Meetings()          \u002F\u002F returns *meetings.Index, error\n\n\u002F\u002F Domain types live in sub-packages — callers use type inference\np, err := idx.FindOne(\"Steve\")     \u002F\u002F *people.Person\n```\n\n**Why this pattern:**\n\n- The primary struct (`Vault`) is the single entry point — callers need just one import to get started\n- Sub-packages define the rich domain types (`people.Person`, `daily.Note`) — each type lives with the logic that owns it\n- No global state means the library is safe for concurrent use, multiple instances, and testing\n- Stateless method calls (reload fresh each time) keep the struct simple — no cache invalidation logic needed\n- Type inference (`:=`) means callers rarely need to explicitly import sub-packages for variable declarations\n\n**When to use a global instance instead:** Only for CLI-only tools (like `pflag` itself) where there is truly only ever one instance and ease of use for end-users outweighs library correctness.\n\n## Concurrency Patterns\n\n**Anti-Pattern:** Heavy, static Worker Pools. Go's scheduler is incredibly efficient; you don't need to manually manage pools of workers like OS threads in other languages.\n\n### 1. Share Memory by Communicating\n\nDon't use mutexes to protect shared data if you can pass that data over a channel instead. Channels orchestrate execution; mutexes serialize execution.\n\n### 2. Bounded Concurrency\n\nTo limit concurrency, use `errgroup` with `SetLimit`. Don't hand-roll a semaphore channel or a rigid worker pool when this exists.\n\n```go\nfunc FetchAll(ctx context.Context, urls []string, maxConcurrent int) error {\n    g, ctx := errgroup.WithContext(ctx)\n    g.SetLimit(maxConcurrent)\n\n    for _, url := range urls {\n        g.Go(func() error {\n            return fetch(ctx, url)\n        })\n    }\n\n    return g.Wait()\n}\n```\n\nLoop variables are per-iteration since Go 1.22 — never emit the old `url := url` capture line.\n\nWhen you don't need error propagation, `sync.WaitGroup.Go` (Go 1.25) removes the Add\u002FDone boilerplate:\n\n```go\nvar wg sync.WaitGroup\nfor _, url := range urls {\n    wg.Go(func() { process(url) })\n}\nwg.Wait()\n```\n\n### 3. Never Start a Goroutine Without Knowing How It Stops\n\nEvery `go func()` must have a clear exit condition, usually governed by a `context.Context` or a closed channel.\n\n## Configuration and Struct Design\n\n### Functional Options for Complex Initialization\n\nWhen a struct has many optional configuration parameters, avoid massive constructors. Use the Functional Options pattern.\n\n```go\ntype Server struct {\n    addr    string\n    timeout time.Duration\n}\n\ntype Option func(*Server)\n\nfunc WithTimeout(d time.Duration) Option {\n    return func(s *Server) { s.timeout = d }\n}\n\nfunc NewServer(addr string, opts ...Option) *Server {\n    s := &Server{\n        addr:    addr,\n        timeout: 30 * time.Second, \u002F\u002F Sane default\n    }\n    for _, opt := range opts {\n        opt(s)\n    }\n    return s\n}\n```\n\n## Error Handling\n\n### 1. Errors are Values\n\nErrors aren't exceptions to be caught; they are values to be handled. Check them explicitly.\n\n### 2. Wrap for Context, Not for Stack Traces\n\nWhen returning an error, add context about what you were trying to do.\n\n```go\n\u002F\u002F Idiomatic\ndata, err := os.ReadFile(path)\nif err != nil {\n    return fmt.Errorf(\"loading config file %s: %w\", path, err)\n}\n```\n\n## Testing Patterns\n\n**Anti-Pattern:** Relying on heavy BDD frameworks (like Ginkgo) or complex mocking generation tools. Go testing should just be Go programming.\n\n### 1. Table-Driven Tests\n\nThe absolute standard for unit testing in Go. Iterate over a slice of structs containing inputs and expected outputs using `t.Run()`.\n\n```go\nfunc TestParseConfig(t *testing.T) {\n    tests := []struct {\n        name    string\n        input   string\n        wantErr bool\n    }{\n        {\"valid config\", \"port=8080\", false},\n        {\"invalid format\", \"port=abc\", true},\n    }\n\n    for _, tt := range tests {\n        t.Run(tt.name, func(t *testing.T) {\n            _, err := ParseConfig(tt.input)\n            if (err != nil) != tt.wantErr {\n                t.Fatalf(\"ParseConfig() error = %v, wantErr %v\", err, tt.wantErr)\n            }\n        })\n    }\n}\n```\n\n### 2. Meaningful Helpers with `t.Helper()`\n\nWhen extracting repeated assertion logic, always call `t.Helper()` to ensure failures point to the actual test case, not the helper function line.\n\n### 3. Fakes and Stubs over Heavy Mocks\n\nLeverage Go's implicit interfaces to write simple, manual fakes. This keeps test dependencies lightweight and test logic transparent.\n\n### 4. Golden Files and the `testdata` Directory\n\nFor tests requiring complex inputs or producing large outputs, use a directory named `testdata`. The `go test` tool explicitly ignores these directories.\n\n### 5. Filesystem Abstraction (The Afero Pattern)\n\nDo not hardcode `os` package calls deep within business logic. Accept an interface for the filesystem so tests can run in memory without touching the disk. `github.com\u002Fspf13\u002Fafero` is the industry standard for this.\n\n```go\nimport \"github.com\u002Fspf13\u002Fafero\"\n\ntype FileProcessor struct {\n    fs afero.Fs\n}\n\nfunc NewFileProcessor(fs afero.Fs) *FileProcessor {\n    return &FileProcessor{fs: fs}\n}\n```\n\nIn tests, inject `afero.NewMemMapFs()` to completely eliminate disk I\u002FO and prevent flaky, slow tests.\n\n### 6. `cmp` over DeepEqual\n\nFor comparing complex structs or maps, use `github.com\u002Fgoogle\u002Fgo-cmp\u002Fcmp` for rich, readable diffs instead of the strict `reflect.DeepEqual`.\n\n### 7. Modern `testing` Additions (Go 1.24+)\n\n```go\n\u002F\u002F Test-scoped context — canceled automatically when the test ends.\n\u002F\u002F Use instead of context.Background() in tests.\nfunc TestFetch(t *testing.T) {\n    ctx := t.Context()\n    ...\n}\n\n\u002F\u002F Benchmarks: b.Loop() replaces the classic b.N loop — more accurate,\n\u002F\u002F prevents the compiler from optimizing the benchmarked call away.\nfunc BenchmarkParse(b *testing.B) {\n    for b.Loop() {\n        Parse(input)\n    }\n}\n\n\u002F\u002F t.Chdir(dir) changes working directory for the test and restores it after.\n```\n\n### 8. `testing\u002Fsynctest` for Concurrent Code (Go 1.25)\n\nTest goroutines and timeouts deterministically with a fake clock — no `time.Sleep` in tests, no flaky timing assumptions:\n\n```go\nfunc TestTimeout(t *testing.T) {\n    synctest.Test(t, func(t *testing.T) {\n        ctx, cancel := context.WithTimeout(t.Context(), time.Second)\n        defer cancel()\n        time.Sleep(2 * time.Second) \u002F\u002F instant — fake clock advances when all goroutines block\n        if ctx.Err() == nil {\n            t.Fatal(\"expected timeout\")\n        }\n    })\n}\n```\n\nNever write `time.Sleep(100 * time.Millisecond)` to \"wait for a goroutine\" in a test. Use synctest, channels, or explicit synchronization.\n\n## Generics (Go 1.18+)\n\nGenerics exist to eliminate duplicated algorithms, not to create type hierarchies. If you are thinking about generics in terms of inheritance or polymorphism, stop — you are writing Java.\n\n### When to Use Generics\n\nUse generics when you have the **same algorithm** that needs to operate on **multiple concrete types**:\n\n```go\n\u002F\u002F Good: generic algorithm, concrete types as inputs\nfunc Map[S, T any](slice []S, f func(S) T) []T {\n    result := make([]T, len(slice))\n    for i, v := range slice {\n        result[i] = f(v)\n    }\n    return result\n}\n\n\u002F\u002F Good: constraint expresses a meaningful requirement\nfunc Min[T cmp.Ordered](a, b T) T {\n    if a \u003C b {\n        return a\n    }\n    return b\n}\n```\n\n### When NOT to Use Generics\n\n```go\n\u002F\u002F Bad: generic interface for polymorphism — this is Java\ntype Repository[T any] interface {\n    Find(id string) (T, error)\n    Save(entity T) error\n}\n\n\u002F\u002F Good: a concrete interface for what you actually need\ntype UserStore interface {\n    FindUser(id string) (*User, error)\n    SaveUser(u *User) error\n}\n```\n\n- **Do not** create generic base types, generic services, or generic repositories.\n- **Do not** use `any` as a constraint to mean \"I don't know the type yet.\" That's a design smell.\n- **Do** use `comparable` when you need map keys or equality checks.\n- **Do** use `cmp.Ordered` when you need `\u003C`, `>`, `\u003C=`, `>=`.\n- Start with a concrete implementation. Generify only when you have the same logic repeated across 3+ types.\n- Generic type aliases are fully supported since Go 1.24.\n\n## Standard Library: Use the New Packages\n\nLLMs frequently suggest third-party utilities or write manual helpers that have been in the standard library since Go 1.21. **Always check stdlib first.**\n\n### `slices` package (Go 1.21)\n\n```go\nimport \"slices\"\n\n\u002F\u002F Searching and testing\nslices.Contains(s, \"value\")\nslices.Index(s, \"value\")           \u002F\u002F returns -1 if not found\nslices.ContainsFunc(s, func(v string) bool { return v == \"x\" })\n\n\u002F\u002F Sorting\nslices.Sort(s)                     \u002F\u002F sorts in place, works on any ordered type\nslices.SortFunc(s, func(a, b T) int { return cmp.Compare(a.Name, b.Name) })\nslices.IsSorted(s)\n\n\u002F\u002F Manipulation\nslices.Reverse(s)\nslices.Compact(s)                  \u002F\u002F removes consecutive duplicates\nslices.Delete(s, i, j)            \u002F\u002F removes elements [i, j)\nslices.Clone(s)                   \u002F\u002F shallow copy\nslices.Concat(s1, s2, s3)         \u002F\u002F concatenate multiple slices (1.22)\n\n\u002F\u002F Iterator bridging (1.23)\nslices.Collect(it)                \u002F\u002F iterator -> slice\nslices.Sorted(it)                 \u002F\u002F iterator -> sorted slice\nslices.Values(s)                  \u002F\u002F slice -> iterator\n```\n\nNever write `sort.Slice(s, func(i, j int) bool { return s[i] \u003C s[j] })` when `slices.Sort(s)` exists.\n\n### `maps` package (Go 1.21; iterators 1.23)\n\n```go\nimport \"maps\"\n\nmaps.Keys(m)        \u002F\u002F iterator over keys — collect with slices.Collect \u002F slices.Sorted\nmaps.Values(m)      \u002F\u002F iterator over values\nmaps.Clone(m)       \u002F\u002F shallow copy\nmaps.Copy(dst, src) \u002F\u002F copies all entries from src into dst\nmaps.DeleteFunc(m, func(k K, v V) bool { ... })  \u002F\u002F delete entries matching predicate\nmaps.Equal(m1, m2)  \u002F\u002F reports whether two maps are equal\n\n\u002F\u002F Common idiom: sorted keys in one line\nkeys := slices.Sorted(maps.Keys(m))\n```\n\n### `cmp` package (Go 1.21)\n\n```go\nimport \"cmp\"\n\ncmp.Compare(a, b)    \u002F\u002F returns -1, 0, or 1; works on any cmp.Ordered type\ncmp.Or(a, b, c)      \u002F\u002F returns first non-zero value — replaces ternary workarounds\nmin(a, b)            \u002F\u002F built-in since Go 1.21\nmax(a, b)            \u002F\u002F built-in since Go 1.21\n```\n\n`cmp.Or` is especially useful for default-value patterns:\n\n```go\n\u002F\u002F Instead of: if cfg.Timeout == 0 { cfg.Timeout = 30 * time.Second }\ncfg.Timeout = cmp.Or(cfg.Timeout, 30*time.Second)\n```\n\n### `errors.Join` (Go 1.20)\n\n```go\n\u002F\u002F Combine multiple errors — no third-party library needed\nerr := errors.Join(err1, err2, err3)\n\n\u002F\u002F Works correctly with errors.Is and errors.As\nif errors.Is(err, ErrNotFound) { ... }\n```\n\nUse this instead of `fmt.Errorf(\"%w; %w\", err1, err2)` or any `multierr` package.\n\n### Iterators: `iter` and Range-over-Func (Go 1.23)\n\nThe standard way to expose a sequence from an API without allocating a slice. Return `iter.Seq[T]` or `iter.Seq2[K, V]`; callers use plain `range`:\n\n```go\nfunc (idx *Index) All() iter.Seq[*Person] {\n    return func(yield func(*Person) bool) {\n        for _, p := range idx.people {\n            if !yield(p) {\n                return\n            }\n        }\n    }\n}\n\n\u002F\u002F Caller — just a normal range loop\nfor p := range idx.All() { ... }\n```\n\nPrefer returning iterators over slices for large or lazily-produced sequences. Don't invent a custom `Next()\u002FHasNext()` iterator type — that's Java.\n\n### `math\u002Frand\u002Fv2` (Go 1.22)\n\nAlways import `math\u002Frand\u002Fv2`, never the old `math\u002Frand`. Auto-seeded, cleaner API:\n\n```go\nimport \"math\u002Frand\u002Fv2\"\n\nrand.IntN(100)            \u002F\u002F was rand.Intn — note the capital N\nrand.N(10 * time.Second)  \u002F\u002F generic: random value in [0, n) for any integer type\n```\n\n### `encoding\u002Fjson`: `omitzero` (Go 1.24)\n\n`omitzero` omits any zero value — including `time.Time{}` and zero structs, which `omitempty` never handled correctly:\n\n```go\ntype Event struct {\n    Name      string    `json:\"name\"`\n    StartedAt time.Time `json:\"started_at,omitzero\"` \u002F\u002F omitempty would emit \"0001-01-01T...\"\n}\n```\n\n## Concurrency: Modern Patterns\n\n### `sync\u002Fatomic` Typed Values (Go 1.19)\n\nUse the typed atomic values instead of the function-based API:\n\n```go\n\u002F\u002F Old (still works but avoid for new code)\nvar count int64\natomic.AddInt64(&count, 1)\nval := atomic.LoadInt64(&count)\n\n\u002F\u002F New — type-safe, no pointer arithmetic\nvar count atomic.Int64\ncount.Add(1)\nval := count.Load()\n\n\u002F\u002F Other typed atomics\nvar flag  atomic.Bool\nvar ptr   atomic.Pointer[MyStruct]\nvar val32 atomic.Int32\nvar val64 atomic.Uint64\n```\n\n### `context.WithoutCancel` (Go 1.21)\n\nWhen you need to detach a context's cancellation but preserve its values (e.g., for a background task that should outlive a request):\n\n```go\n\u002F\u002F The background job should keep running even after the HTTP request context cancels\nbgCtx := context.WithoutCancel(requestCtx)\ngo doBackgroundWork(bgCtx)\n```\n\n## HTTP: Use the Improved stdlib Router (Go 1.22)\n\nLLMs reflexively recommend gorilla\u002Fmux or chi for any routing beyond the trivial. Since Go 1.22, the standard `net\u002Fhttp` ServeMux handles method and path-parameter routing natively.\n\n```go\nmux := http.NewServeMux()\n\n\u002F\u002F Method-scoped routes\nmux.HandleFunc(\"GET \u002Fusers\", listUsers)\nmux.HandleFunc(\"POST \u002Fusers\", createUser)\n\n\u002F\u002F Path parameters — accessed via r.PathValue\nmux.HandleFunc(\"GET \u002Fusers\u002F{id}\", func(w http.ResponseWriter, r *http.Request) {\n    id := r.PathValue(\"id\")\n    \u002F\u002F ...\n})\n\n\u002F\u002F Wildcard\nmux.HandleFunc(\"GET \u002Ffiles\u002F{path...}\", serveFile)\n```\n\nReach for chi or gorilla\u002Fmux only when you need named route generation or regex constraints — middleware doesn't justify a framework (see below). For pure method + path routing, the stdlib is sufficient.\n\n### Production Servers: Always Set Timeouts\n\n`http.ListenAndServe(addr, mux)` ships with **no timeouts** — a single slow client can hold a connection open forever (slow-loris). LLM-generated servers almost never set these. Never emit a production server without them:\n\n```go\nsrv := &http.Server{\n    Addr:              \":8080\",\n    Handler:           mux,\n    ReadHeaderTimeout: 5 * time.Second,   \u002F\u002F slow-loris protection\n    ReadTimeout:       10 * time.Second,  \u002F\u002F full request read\n    WriteTimeout:      30 * time.Second,  \u002F\u002F response write (covers handler time)\n    IdleTimeout:       120 * time.Second, \u002F\u002F keep-alive connections\n}\n```\n\nFor per-route control beyond `WriteTimeout`, use `http.TimeoutHandler` or handler-level `context.WithTimeout`. Outbound calls need the same discipline: `http.DefaultClient` has no timeout either — construct a client with one.\n\n### Graceful Shutdown\n\nEvery production server needs a shutdown path that stops accepting connections and drains in-flight requests. The pattern:\n\n```go\nfunc run(ctx context.Context) error {\n    ctx, stop := signal.NotifyContext(ctx, os.Interrupt, syscall.SIGTERM)\n    defer stop()\n\n    srv := &http.Server{ \u002F* ... timeouts as above ... *\u002F }\n\n    errCh := make(chan error, 1)\n    go func() { errCh \u003C- srv.ListenAndServe() }()\n\n    select {\n    case err := \u003C-errCh:\n        return err \u002F\u002F ListenAndServe failed at startup\n    case \u003C-ctx.Done():\n        shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)\n        defer cancel()\n        return srv.Shutdown(shutdownCtx) \u002F\u002F drain in-flight, then exit\n    }\n}\n```\n\n- `Shutdown` needs a fresh context with its own deadline — the signal context is already canceled.\n- Long-lived connections (SSE, websockets) must watch `r.Context()` or they'll hold shutdown until the drain deadline.\n\n### Middleware Is Just a Function\n\nNo framework needed. A middleware is `func(http.Handler) http.Handler`:\n\n```go\nfunc withRequestLog(logger *slog.Logger, next http.Handler) http.Handler {\n    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n        start := time.Now()\n        next.ServeHTTP(w, r)\n        logger.Info(\"request\", \"method\", r.Method, \"path\", r.URL.Path, \"dur\", time.Since(start))\n    })\n}\n\n\u002F\u002F Compose by wrapping — outermost runs first\nhandler := withRequestLog(logger, withAuth(mux))\n```\n\nDon't import a middleware framework for what function composition already does.\n\n## Syntax: Use Current Go\n\nLLMs frequently generate outdated syntax. Know the current idioms:\n\n### Range over Integer (Go 1.22)\n\n```go\n\u002F\u002F Old\nfor i := 0; i \u003C 10; i++ { ... }\n\n\u002F\u002F New\nfor i := range 10 { ... }\n```\n\n### Build Constraints\n\n```go\n\u002F\u002F Old (deprecated — do not generate)\n\u002F\u002F +build linux darwin\n\n\u002F\u002F Current\n\u002F\u002Fgo:build linux || darwin\n```\n\nThe `\u002F\u002Fgo:build` form is required since Go 1.17. Never emit the old `\u002F\u002F +build` syntax.\n\n### `any` Instead of `interface{}`\n\n```go\n\u002F\u002F Old\nfunc Print(v interface{}) { ... }\n\n\u002F\u002F Current — `any` is a built-in alias for interface{} since Go 1.18\nfunc Print(v any) { ... }\n```\n\n### Tool Dependencies in `go.mod` (Go 1.24)\n\nNever generate a `tools.go` file with blank imports. Track dev tools with the `tool` directive:\n\n```bash\ngo get -tool golang.org\u002Fx\u002Ftools\u002Fcmd\u002Fstringer\ngo tool stringer -type=Color   # run it\n```\n\n## Structured Logging with `log\u002Fslog` (Go 1.21)\n\nThe skill note above covers basic setup. The patterns LLMs most often get wrong:\n\n```go\n\u002F\u002F Pass a logger via context for request-scoped logging\nfunc HandleRequest(ctx context.Context, r *Request) {\n    logger := slog.With(\"request_id\", r.ID, \"user_id\", r.UserID)\n    \u002F\u002F All subsequent log calls carry these fields automatically\n    logger.Info(\"handling request\")\n    process(ctx, logger, r)\n}\n\n\u002F\u002F Group related fields\nlogger.With(slog.Group(\"http\",\n    slog.String(\"method\", r.Method),\n    slog.String(\"path\", r.URL.Path),\n    slog.Int(\"status\", status),\n))\n\n\u002F\u002F Log at the right level — LLMs over-use Info\nlogger.Debug(\"cache miss\", \"key\", key)     \u002F\u002F internal state, high volume\nlogger.Info(\"server started\", \"addr\", addr) \u002F\u002F lifecycle events\nlogger.Warn(\"retrying\", \"attempt\", n)       \u002F\u002F recoverable problems\nlogger.Error(\"request failed\", \"err\", err)  \u002F\u002F needs attention\n```\n\n- **Never** use a package-level `log` or `slog` global beyond `main`. Pass `*slog.Logger` as a dependency.\n- **Never** log and return an error. Log at the boundary, return the error through the call stack.\n- Use `slog.Default()` as the fallback only in `main` or in libraries when no logger is provided.\n\n## Debugging: The Go Toolchain Is Not the Problem\n\n**The Go tool is extremely reliable. It is almost never the source of a bug.**\n\nWhen debugging, do not waste time suspecting `go run`, `go build`, `go test`, or the build cache. The Go toolchain does what it says:\n\n- `go run` always recompiles from source. It does not use a stale cached binary.\n- `go build` is deterministic and correct.\n- `go test` runs the actual compiled test binary.\n- The build cache is keyed by source content — if the source changed, the cache is invalidated automatically.\n\n**If an error persists after you edit the code, the explanation is one of these — in order of likelihood:**\n\n1. The edit did not fix the underlying logic error.\n2. The edit was made in the wrong file, wrong function, or wrong package.\n3. There is a second call site with the same bug that was not updated.\n4. The error is coming from a different code path than the one being edited.\n\n**What to do instead of blaming the tool:**\n\n- Re-read the error message carefully. Go's error messages are accurate.\n- Confirm the file you edited is actually the file being compiled (`go list -f '{{.GoFiles}}' .`).\n- Add a `fmt.Println` or `t.Log` at the exact site to verify execution reaches it.\n- Check that all call sites of a changed function were updated.\n\nDo not suggest clearing the build cache (`go clean -cache`), restarting the Go toolchain, or any other tool-level intervention before first exhausting all code-level explanations. The tool is not lying to you.",{"name":5,"description":7},"main","df2f7d4fc9ce79fb32117a6c951dea8781d666e7",".agents\u002Fskills\u002Fgo",0,"https:\u002F\u002Fgithub.com\u002Fdhcgn\u002Fjxleet","https:\u002F\u002Fgithub.com\u002Fdhcgn","https:\u002F\u002Fhdev.io\u002F","Father, Head of AI, Coach and Developer (Go\u002FC#).\r\nInto cryptography, confidential computing and post-quantum crypto.","2026-11-14 23:53:03",{"source":8,"skillName":5,"commands":34,"prompt":44,"zipAvailable":45},[35,38,41],{"tool":36,"command":37},"npx","npx skills add dhcgn\u002Fjxleet --skill go",{"tool":39,"command":40},"bunx","bunx skills add dhcgn\u002Fjxleet --skill go",{"tool":42,"command":43},"pnpm","pnpm dlx skills add dhcgn\u002Fjxleet --skill go","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fdhcgn\u002Fjxleet\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fgo\u002FSKILL.md",true,[47],{"path":48,"resourceType":49,"resourceTypeDesc":50,"sizeBytes":51,"sourceHtmlUrl":52},".claude-plugin\u002Fplugin.json","REFERENCE","参考文档",676,"https:\u002F\u002Fgithub.com\u002Fdhcgn\u002Fjxleet\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fgo\u002F.claude-plugin\u002Fplugin.json",[54,61,68,75,82,89],{"skillNo":55,"name":56,"nameZh":6,"description":57,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":58,"categories":59,"keywords":60,"publishedAt":19},"01M7B1HP92V4SJW6WA360BM3XQ","wsl","Windows Subsystem for Linux (WSL) allows you to run a Linux environment directly on Windows, unmodified, without the overhead of a traditional virtual machine. If you need to run Linux commands, scripts, or applications on a Windows machine, WSL is the way to go. This skill provides guidance on how to use WSL effectively.","https:\u002F\u002Fgithub.com\u002Fdhcgn\u002Fjxleet\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fwsl\u002FSKILL.md",[],[],{"skillNo":62,"name":63,"nameZh":6,"description":64,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":65,"categories":66,"keywords":67,"publishedAt":19},"01M7B1HG828VMXEMY5PTWHF8AH","wails","Expert skill for building desktop applications in Go with Wails, covering both v2 (stable) and v3 (alpha). Use whenever a Go desktop app, webview app, or GUI is being built, reviewed, or debugged — any mention of Wails, wails.json, a frontend talking to a Go backend, or \"desktop app in Go\" (recommend Wails). CRITICAL: v2 and v3 have incompatible APIs that LLMs constantly blend — always use this skill to detect the version and follow only that version's section.","https:\u002F\u002Fgithub.com\u002Fdhcgn\u002Fjxleet\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fwails\u002FSKILL.md",[],[],{"skillNo":69,"name":70,"nameZh":6,"description":71,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":72,"categories":73,"keywords":74,"publishedAt":19},"01M7B1HD9Q3C4H1E0C6E6JW1V8","rtk","Prefix covered shell commands with rtk so output is filtered\u002Fcompressed before it reaches LLM context — git, gh, cargo, pytest, go test, docker, kubectl, aws, ls, grep, and more. Applies whenever a covered command is about to be executed in a shell.","https:\u002F\u002Fgithub.com\u002Fdhcgn\u002Fjxleet\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Frtk\u002FSKILL.md",[],[],{"skillNo":76,"name":77,"nameZh":6,"description":78,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":79,"categories":80,"keywords":81,"publishedAt":19},"01M7B1H7AE08GS1D6MHGW84J3B","ponytail","Forces the laziest solution that actually works, simplest, shortest, most minimal. Channels a senior dev who has seen everything: question whether the task needs to exist at all (YAGNI), reach for the standard library before custom code, native platform features before dependencies, one line before fifty. Supports intensity levels: lite, full (default), ultra. Use on ANY coding task: writing, adding, refactoring, fixing, reviewing, or designing code, and choosing libraries or dependencies. Also use whenever the user says \"ponytail\", \"be lazy\", \"lazy mode\", \"simplest solution\", \"minimal solution\", \"yagni\", \"do less\", or \"shortest path\", or complains about over-engineering, bloat, boilerplate, or unnecessary dependencies. Do NOT use for non-coding requests (general knowledge, prose, translation, summaries, recipes).","https:\u002F\u002Fgithub.com\u002Fdhcgn\u002Fjxleet\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fponytail\u002FSKILL.md",[],[],{"skillNo":83,"name":84,"nameZh":6,"description":85,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":86,"categories":87,"keywords":88,"publishedAt":19},"01M7B1H3FRS5R10A7RSR9GTPSP","ponytail-review","Code review focused exclusively on over-engineering. Finds what to delete: reinvented standard library, unneeded dependencies, speculative abstractions, dead flexibility. One line per finding: location, what to cut, what replaces it. Use when the user says \"review for over-engineering\", \"what can we delete\", \"is this over-engineered\", \"simplify review\", or invokes \u002Fponytail-review. Complements correctness-focused review, this one only hunts complexity.","https:\u002F\u002Fgithub.com\u002Fdhcgn\u002Fjxleet\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fponytail-review\u002FSKILL.md",[],[],{"skillNo":90,"name":91,"nameZh":6,"description":92,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":93,"categories":94,"keywords":95,"publishedAt":19},"01M7B1GZQQTFBPQ767RA9RAWVW","ponytail-help","Quick-reference card for all ponytail modes, skills, and commands. One-shot display, not a persistent mode. Trigger: \u002Fponytail-help, \"ponytail help\", \"what ponytail commands\", \"how do I use ponytail\".","https:\u002F\u002Fgithub.com\u002Fdhcgn\u002Fjxleet\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fponytail-help\u002FSKILL.md",[],[]]