@srobroek/pi-lang-go 0.0.0-stage → 0.9.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,118 @@
1
+ ---
2
+ name: lang-go-packaging
3
+ description: Use for Go module and package layout (monorepo, cmd/, internal/, go.work, build tags, tool directive, depguard).
4
+ metadata:
5
+ opencode/autoinvoke: false
6
+ ---
7
+
8
+ # Go Packaging
9
+
10
+ Sources: [Organizing a Go module](https://go.dev/doc/modules/layout), [Go modules reference: workspaces](https://go.dev/ref/mod#workspaces), `go help buildconstraint`, `go help packages` (Go 1.27), [golangci-lint depguard](https://golangci-lint.run/docs/linters/configuration/#depguard).
11
+
12
+ Package design (consumer-owned interfaces, no `utils` package) is the `quality-code-design`
13
+ skill's `go.md` reference. This skill is the module mechanics.
14
+
15
+ ## One module first
16
+
17
+ ```text
18
+ go.mod module example.com/shop
19
+ cmd/api/main.go one directory per binary; main stays thin
20
+ cmd/worker/main.go
21
+ internal/billing/ shared by both binaries, importable by nothing outside the module tree
22
+ internal/storage/
23
+ ```
24
+
25
+ - A monorepo whose services ship together is one module: shared code under
26
+ `internal/`, binaries under `cmd/<name>`. One `go.mod`, one dependency graph, one
27
+ `go test ./...`.
28
+ - `internal/` is enforced by the go tool: `a/b/internal/c` is importable only by
29
+ code rooted at `a/b`. Put code there by default; move it out only when another
30
+ repository must import it, because everything outside `internal/` is public API.
31
+ - The compiler rejects import cycles. A cycle means two packages share a concept;
32
+ move it to a third package both import, or merge them.
33
+ - Split into several modules only when parts are versioned and released
34
+ separately (a public client library, a tool with different dependencies). Each
35
+ extra module adds its own `go.mod`, tags (`sub/v1.2.0`) and tidy step.
36
+ - A module at major version 2 or later has the `/v2` suffix in its module path and
37
+ in every import.
38
+
39
+ ## go.work for local multi-module development
40
+
41
+ ```sh
42
+ go work init ./api ./client # writes go.work with use directives
43
+ go work use ./tools # add another module
44
+ GOWORK=off go test ./... # check one module against its own go.mod only
45
+ ```
46
+
47
+ `go.work` makes local modules override each other's required versions. The Go
48
+ modules reference calls committing `go.work` generally inadvisable: CI would build
49
+ against the local versions, not what each `go.mod` requires. Keep it out of version
50
+ control (or, for a deliberately committed workspace, still run `GOWORK=off` per module
51
+ in CI). From a workspace root without `go.mod`, `./...` matches nothing: use the `work`
52
+ pattern (`go test work`, Go 1.25+) or `go -C ./api test ./...`.
53
+
54
+ ## Tools pinned in go.mod
55
+
56
+ ```sh
57
+ go get -tool golang.org/x/tools/cmd/stringer # Go 1.24+: records a tool directive
58
+ go tool stringer -type=State # runs the pinned version
59
+ ```
60
+
61
+ This replaces the old `tools.go` blank-import file and keeps generators and linters at
62
+ the version `go.mod` records.
63
+
64
+ ## Build tags for debug-only code
65
+
66
+ ```go
67
+ // debug_on.go
68
+ //go:build debug
69
+
70
+ package app
71
+
72
+ const debugEnabled = true
73
+ ```
74
+
75
+ ```go
76
+ // debug_off.go
77
+ //go:build !debug
78
+
79
+ package app
80
+
81
+ const debugEnabled = false
82
+ ```
83
+
84
+ `if debugEnabled { … }` is removed from builds without `-tags debug`, and files tagged
85
+ `debug` (debug endpoints, extra assertions) are not compiled at all. The constraint
86
+ line comes before `package`, followed by a blank line. Vet and test both variants:
87
+ `go vet ./...` and `go vet -tags debug ./...`.
88
+
89
+ ## Import rules with depguard
90
+
91
+ Enforce layering in CI instead of in review, with golangci-lint v2:
92
+
93
+ ```yaml
94
+ # .golangci.yml
95
+ version: "2"
96
+ linters:
97
+ enable: [depguard]
98
+ settings:
99
+ depguard:
100
+ rules:
101
+ domain:
102
+ files: ["**/internal/domain/**"]
103
+ deny:
104
+ - pkg: "database/sql"
105
+ desc: the domain uses the repository interface; SQL lives in internal/storage
106
+ - pkg: "net/http"
107
+ desc: transport belongs in internal/httpapi
108
+ ```
109
+
110
+ Each rule names the files it applies to and the packages they may not import
111
+ (`desc` is the message). `files` globs match the full path: `**/internal/domain/**`
112
+ matches, `**/internal/domain/**/*.go` silently matches nothing, so prove a new rule by
113
+ adding a forbidden import and watching it fail. Enabling depguard with no rules allows
114
+ only the standard library everywhere, so always define rules.
115
+
116
+ A `go.work` in a parent directory also captures the module: when `go` or
117
+ golangci-lint reports `directory prefix . does not contain modules listed in go.work`,
118
+ run with `GOWORK=off`.
@@ -0,0 +1,63 @@
1
+ ---
2
+ name: lang-go-profiling
3
+ description: Use for Go profiling and benchmarks (go test -bench, pprof CPU/heap/block profiles, go tool trace, benchstat).
4
+ metadata:
5
+ opencode/autoinvoke: false
6
+ ---
7
+
8
+ # Go
9
+
10
+ Sources: [Go diagnostics](https://go.dev/doc/diagnostics), [`testing`](https://pkg.go.dev/testing), [`net/http/pprof`](https://pkg.go.dev/net/http/pprof), [benchstat](https://pkg.go.dev/golang.org/x/perf/cmd/benchstat). Checked against `go help testflag` on Go 1.27.
11
+
12
+ Tooling only. The method (target, fixed workload, baseline with variance, one change at a time, re-measure, report) is the `quality-profiling` skill; load it first if it is not loaded.
13
+
14
+ ## Benchmarks and profiles from tests
15
+
16
+ ```go
17
+ func BenchmarkParse(b *testing.B) {
18
+ in := loadFixture() // setup outside the loop is not timed
19
+ b.ReportAllocs()
20
+ for b.Loop() { // Go 1.24+; older code uses for i := 0; i < b.N; i++
21
+ Parse(in)
22
+ }
23
+ }
24
+ ```
25
+
26
+ ```sh
27
+ go test -run='^$' -bench=Parse -benchmem -count=10 > old.txt
28
+ # make the change
29
+ go test -run='^$' -bench=Parse -benchmem -count=10 > new.txt
30
+ benchstat old.txt new.txt # go install golang.org/x/perf/cmd/benchstat@latest
31
+
32
+ go test -run='^$' -bench=Parse -cpuprofile cpu.out -memprofile mem.out
33
+ go test -run='^$' -bench=Parse -blockprofile block.out -mutexprofile mutex.out
34
+ go test -run='^$' -bench=Parse -trace trace.out
35
+ ```
36
+
37
+ benchstat reports the change with a confidence interval and marks it `~` when not significant; run `-count` of 10 or more.
38
+
39
+ ## Live services
40
+
41
+ ```go
42
+ import _ "net/http/pprof" // registers /debug/pprof/ on http.DefaultServeMux; serve it on an internal port only
43
+ ```
44
+
45
+ ```sh
46
+ go tool pprof -http=:8081 'http://localhost:6060/debug/pprof/profile?seconds=30' # CPU
47
+ go tool pprof -http=:8081 http://localhost:6060/debug/pprof/heap # live heap (-sample_index=alloc_space for allocations)
48
+ go tool pprof http://localhost:6060/debug/pprof/goroutine # stuck or leaked goroutines
49
+ go tool pprof http://localhost:6060/debug/pprof/block # needs runtime.SetBlockProfileRate; mutex needs SetMutexProfileFraction
50
+ curl -o trace.out 'http://localhost:6060/debug/pprof/trace?seconds=5' && go tool trace trace.out
51
+ ```
52
+
53
+ ## Reading pprof
54
+
55
+ `top` / `top -cum` rank by self / cumulative time; `list Func` shows per-line cost; `-http` opens graph, flame graph and source views. Compare runs with `go tool pprof -diff_base old.pprof new.pprof`. The CPU profile shows on-CPU time only; latency spent waiting shows in the block, mutex and goroutine profiles and the execution trace (scheduler, GC, syscalls).
56
+
57
+ ## Pitfalls
58
+
59
+ - The compiler removes work whose result is unused; assign results to a package-level sink, or rely on `b.Loop()`, which keeps the loop body's calls alive.
60
+ - `-benchmem` allocations per op often matter more than ns/op: each allocation costs GC time later, outside the benchmark.
61
+ - `GOMAXPROCS` defaults to the cgroup CPU limit on Linux since Go 1.25; benchmark with the same limit as production.
62
+ - CPU profiles of a mostly idle server are empty; profile under load, and use the block, mutex and goroutine profiles for latency.
63
+ - The heap profile's default `inuse_space` shows live memory; switch to `alloc_space` or `alloc_objects` to find allocation churn.
@@ -0,0 +1,75 @@
1
+ ---
2
+ name: lang-go-quality
3
+ description: Use to run Go build, format, lint, vet, go mod tidy, govulncheck and go test -race checks with the project toolchain.
4
+ metadata:
5
+ opencode/autoinvoke: false
6
+ ---
7
+
8
+ # Go Quality
9
+
10
+ Sources: `go help build`, `go help testflag`, `go help mod tidy`, `go help packages` (Go 1.27), [golangci-lint v2](https://golangci-lint.run/docs/), [govulncheck](https://pkg.go.dev/golang.org/x/vuln/cmd/govulncheck), [race detector](https://go.dev/doc/articles/race_detector).
11
+
12
+ Run the checks through the shell tool from the module root (the directory with
13
+ `go.mod`), in this order. Stop at the first failing step, fix it, rerun that step,
14
+ then continue; later steps on code that does not build only add noise.
15
+
16
+ | Step | Command |
17
+ | --- | --- |
18
+ | Build | `go build ./...` |
19
+ | Format check | `golangci-lint fmt --diff` when `.golangci.yml` enables formatters, otherwise `gofmt -l .` (any output is a failure) |
20
+ | Lint | `golangci-lint run` when the project configures it, otherwise `go vet ./...` |
21
+ | Test | `go test -race ./...` |
22
+ | Module tidy | `go mod tidy -diff` (prints the diff and exits non-zero when `go.mod` or `go.sum` is stale) |
23
+ | Vulnerabilities | `go tool govulncheck ./...` (a `tool` directive in `go.mod`) |
24
+ | Format fix | `golangci-lint fmt`, or `gofmt -w .` |
25
+ | API break (libraries) | `go tool go-apidiff <base-ref>` on PRs and at release |
26
+ | Docs | `go doc ./...` renders; lint doc comments through golangci-lint (`revive` `exported`, `godoclint`) |
27
+ | Dead code (executables) | `go tool deadcode -test ./...` |
28
+
29
+ The scaffold's `golangci-lint` v2 config includes `errcheck`, `govet`, `ineffassign`,
30
+ `staticcheck`, `unused` and explicitly enabled `gosec`; `go vet` alone is not that
31
+ gate. Enable `gocognit` at 15 (golangci-lint's own default reports only above 30) and
32
+ `gocyclo` at 10-12, ratcheting reviewed exceptions. For executable
33
+ packages, `go tool deadcode -test ./...` reports whole-program reachability
34
+ from executable/test roots, unlike declaration-level `unused`/`staticcheck` checks.
35
+ Do not treat that report as proof a library's public API is safe to remove.
36
+
37
+ - After an edit that spans files or packages or changes a signature, run
38
+ `go vet ./...` and `go build ./...` once before handing back (or the project's
39
+ own `make`/task target for them when it has one).
40
+ - Respect the project's formatter. When `.golangci.yml` enables `gofumpt`,
41
+ `goimports` or `gci`, a `gofmt`-only check passes code its CI rejects; when it
42
+ uses plain `gofmt`, do not reformat with `gofumpt`.
43
+ - `-race` is the default for tests: it finds data races only on paths the tests
44
+ run, and costs roughly 2-20× time and 5-10× memory. It needs cgo on Linux
45
+ (`CGO_ENABLED=1` and a C compiler); when it cannot run, run `go test ./...` and
46
+ report `-race` as not run.
47
+ - Narrow to the packages the task touched (`go test -race ./internal/billing/...`)
48
+ when the module is slow, and say so in the report.
49
+ - In a `go.work` workspace, `./...` from a root without `go.mod` matches nothing.
50
+ Use the `work` pattern (`go build work`, `go test -race work`, Go 1.25+) or run per
51
+ module with `go -C ./svc test ./...`. `go mod tidy` is per module:
52
+ `go -C ./svc mod tidy -diff`.
53
+ - Never `go install …@latest` a tool inside a check. Use the binary the project
54
+ has: a `tool` directive in `go.mod` (Go 1.24+, detect with `grep -F <module> go.mod`,
55
+ run with `go tool <name>`), or for `golangci-lint` a binary on `PATH`, because its
56
+ docs advise against `go get -tool` and `go install`. When a tool is missing, recommend
57
+ `go get -tool <pkg>@latest` (`golangci-lint`: `brew install golangci-lint`), ask the user
58
+ before running it, and report the step as not run if they decline.
59
+ - Tool choices per concern, with minimum versions, are in `lang-go-libraries`'s
60
+ `references/quality.md` and `references/testing.md`. For `cgo` code, `go test -asan`
61
+ or `-msan` add memory checking beside `-race`.
62
+
63
+ ## CI
64
+
65
+ Run the same steps in the same order, one job or step per row so the failure is
66
+ named. Use `actions/setup-go` with `go-version-file: go.mod` (its module cache is on
67
+ by default), and install `golangci-lint` with `golangci/golangci-lint-action`, not
68
+ `go install`. Workflow structure, the required `ci-gate` job and action pinning are
69
+ the `toolchain` plugin's `ci-github-actions` skill.
70
+
71
+ After an edit, run the listed format check for changed files. The host may format files automatically; do not rely on that instead of the project check.
72
+
73
+ A missing `go.mod` or toolchain binary means that step did not run. Report it as
74
+ not run, never as a pass. Read failures as the project's actual toolchain output;
75
+ do not invent extra linters.
@@ -0,0 +1,140 @@
1
+ ---
2
+ name: lang-go-testing
3
+ description: Use to write or fix Go tests (table tests, subtests, -race, golden files, fuzzing, httptest, synctest, testify).
4
+ metadata:
5
+ opencode/autoinvoke: false
6
+ ---
7
+
8
+ # Go Testing
9
+
10
+ Sources: [`testing`](https://pkg.go.dev/testing), `go help testflag` (Go 1.27), [Go fuzzing](https://go.dev/doc/security/fuzz/), [`testing/synctest`](https://pkg.go.dev/testing/synctest), [go-cmp](https://pkg.go.dev/github.com/google/go-cmp/cmp).
11
+
12
+ Read [practice.md](references/practice.md) for Go idioms and tool choices. Use
13
+ `quality-testing` for what to test, behavior budgets, maintenance and review rules.
14
+ Follow the existing tests' style first: if the package uses `testify`, keep using
15
+ it; do not add it to a package that does not.
16
+
17
+ ## Table tests with subtests
18
+
19
+ ```go
20
+ func TestParseDuration(t *testing.T) {
21
+ tests := []struct {
22
+ name string
23
+ in string
24
+ want time.Duration
25
+ wantErr bool
26
+ }{
27
+ {name: "minutes", in: "5m", want: 5 * time.Minute},
28
+ {name: "empty", in: "", wantErr: true},
29
+ }
30
+ for _, tt := range tests {
31
+ t.Run(tt.name, func(t *testing.T) {
32
+ t.Parallel()
33
+ got, err := ParseDuration(tt.in)
34
+ if (err != nil) != tt.wantErr {
35
+ t.Fatalf("ParseDuration(%q) error = %v, wantErr %v", tt.in, err, tt.wantErr)
36
+ }
37
+ if got != tt.want {
38
+ t.Errorf("ParseDuration(%q) = %v, want %v", tt.in, got, tt.want)
39
+ }
40
+ })
41
+ }
42
+ }
43
+ ```
44
+
45
+ - Under Go `1.22` language semantics, newly declared loop variables have their own
46
+ per-iteration identity; older language versions still need `tt := tt`. Shared
47
+ referenced data and variables reused with `=` are not isolated.
48
+ - Messages read `Func(input) = got, want want`. `t.Fatalf` stops this subtest,
49
+ `t.Errorf` keeps checking.
50
+ - Compare structs and slices with `cmp.Diff(want, got)` from go-cmp
51
+ (`if d := cmp.Diff(want, got); d != "" { t.Errorf("mismatch (-want +got):\n%s", d) }`),
52
+ not `reflect.DeepEqual`, which says only that they differ. Check errors with
53
+ `errors.Is` / `errors.As`, not by string.
54
+ - Helpers call `t.Helper()` first so failures point at the caller. Use `t.TempDir()`,
55
+ `t.Cleanup`, `t.Context()` (Go 1.24+, cancelled before cleanups run) and
56
+ `t.Chdir` (Go 1.24+). `t.Setenv` and `t.Chdir` cannot be combined with `t.Parallel()`.
57
+ - Black-box tests live in `package foo_test` and use only the exported API; keep
58
+ `package foo` tests for internals that cannot be reached otherwise.
59
+ - `func ExampleParse()` with an `// Output:` comment runs as a test and renders as
60
+ documentation.
61
+
62
+ ## Running
63
+
64
+ ```sh
65
+ go test -race ./... # default; see lang-go-quality
66
+ go test -run 'TestParseDuration/empty$' ./internal/timeparse
67
+ go test -count=1 ./... # bypass the test result cache
68
+ go test -shuffle=on -count=5 ./pkg # flush out order dependence; prints the seed
69
+ gotestsum --junitfile junit.xml -- -race ./... # JUnit for CI; rerun flags only for diagnosis
70
+ go test -failfast ./... # stop after the first failing test
71
+ go test -coverprofile=cover.out ./... && go tool cover -func=cover.out
72
+ ```
73
+
74
+ ## Golden files
75
+
76
+ Store stable, reviewable expected outputs under `testdata/` (ignored as a package)
77
+ and regenerate them behind a flag:
78
+
79
+ ```go
80
+ var update = flag.Bool("update", false, "rewrite golden files")
81
+
82
+ golden := filepath.Join("testdata", tt.name+".golden")
83
+ if *update {
84
+ if err := os.WriteFile(golden, got, 0o644); err != nil { t.Fatal(err) }
85
+ }
86
+ want, err := os.ReadFile(golden)
87
+ if err != nil { t.Fatal(err) }
88
+ ```
89
+
90
+ Run `go test ./pkg -update`, then review the golden diff like code before committing.
91
+ This is a custom flag, not a built-in Go flag. Never auto-update in CI.
92
+
93
+ ## Fuzzing
94
+
95
+ ```go
96
+ func FuzzParse(f *testing.F) {
97
+ f.Add("5m") // seed corpus
98
+ f.Fuzz(func(t *testing.T, in string) {
99
+ d, err := ParseDuration(in)
100
+ if err != nil {
101
+ return // rejecting input is fine; panicking is not
102
+ }
103
+ again, err := ParseDuration(d.String()) // assert an invariant, not an exact value
104
+ if err != nil || again != d {
105
+ t.Errorf("round trip of %q: %v -> %v, %v", in, d, again, err)
106
+ }
107
+ })
108
+ }
109
+ ```
110
+
111
+ ```sh
112
+ go test -run='^$' -fuzz='^FuzzParse$' -fuzztime=60s ./internal/timeparse # one package at a time; always bound it
113
+ ```
114
+
115
+ A failing input is written to `testdata/fuzz/FuzzParse/`; commit it. Plain `go test`
116
+ replays the seeds and that corpus as regular tests, so the bug stays fixed.
117
+
118
+ ## Mutation
119
+
120
+ ```sh
121
+ go tool gremlins unleash --diff origin/main --output=gremlins.json # changed code only
122
+ ```
123
+
124
+ `gremlins` (or avito-tech `go-mutesting` v2 when it cannot parse the code) is not
125
+ installed by default: detect it, recommend `go get -tool github.com/go-gremlins/gremlins/cmd/gremlins@latest`,
126
+ and ask before running it. Scope it to changed or critical packages; never gate on the whole module.
127
+
128
+ ## Time, concurrency and I/O
129
+
130
+ - Use `-race`, `synctest` and `go.uber.org/goleak` (`goleak.VerifyNone(t)`) together on
131
+ concurrent code. Go 1.27 adds a `goroutineleak` `runtime/pprof` profile for live processes.
132
+ - Supported in-process timer/concurrency tests can use
133
+ `synctest.Test(t, func(t *testing.T) { /* scenario */ })` (Go `1.25`+). Fake time
134
+ advances when every goroutine in the bubble is durably blocked;
135
+ `synctest.Wait()` waits for quiescence. Network I/O and mutex waits are not
136
+ durably blocking; this does not replace network integration or explore all schedules.
137
+ - HTTP clients: point them at `httptest.NewServer(handler)`; HTTP handlers: call
138
+ them with `httptest.NewRecorder()` and `httptest.NewRequest`.
139
+ - Slow or external integration tests go behind `//go:build integration` (run with
140
+ `go test -tags integration ./...`) or skip under `testing.Short()`.