BosskuAI Go Development
Use this skill when the code is Go and the answer depends on Go's concurrency model, error conventions, or toolchain rather than on general backend advice.
How this differs from nearby skills
bosskuai-polyglot-engineering: cross-language tradeoffs; this skill is the Go-specific operating manual.bosskuai-api-design: contract shape; this skill implements and hardens the Go handlers behind it.bosskuai-database-engineering: schema and query plans; this skill covers pgx/sqlc usage, pooling, and transaction handling in Go.bosskuai-performance-profiling: generic profiling method; this skill knows pprof, escape analysis, and Go allocation patterns.bosskuai-docker/bosskuai-aws-deployment: packaging and hosting; this skill produces the binary they ship.
Mindset
- Errors are values: wrap with
%w, inspect witherrors.Is/errors.As, handle once, log once. - Every goroutine has an owner, a stop signal, and a way to report its error. No fire-and-forget.
context.Contextis the first parameter of anything that does I/O, waits, or can be cancelled.- Standard library first; a dependency must earn its place. Accept interfaces, return structs; define interfaces where they are consumed.
- Make the zero value useful; keep packages flat and named for what they provide, not what they contain.
Orient before changing anything
go.mod: Go version (loop-variable semantics changed in 1.22;min/max/clearin 1.21; range-over-func in 1.23), module path, replace directives.- Layout:
cmd/<binary>for mains,internal/for private packages, nopkg/unless something is meant for import by others. - Tooling present:
Makefile,golangci.yml,sqlc.yaml, migration tool (goose, golang-migrate, atlas), Dockerfile, CI workflow. Match them. - Framework: net/http (1.22 mux supports methods and wildcards), Echo, Chi, Gin, or gRPC. Do not introduce a second one.
- Toolchain: the
goandtoolchainlines ingo.mod, thegolangimage tag in the Dockerfile and the CI setup must agree, andgo versionshows what runs on this machine. An older toolchain can fail the build, and with the defaultGOTOOLCHAIN=autoa build can download the toolchain thatgo.modasks for. Check the latest stable release on go.dev/dl and write down the date you checked.go list -m -u alllists modules with newer versions.
Rules that catch most Go bugs
- Goroutine leaks: a
selectwithout actx.Done()case, a channel nobody drains,time.Afterinside a loop, a worker withouterrgroup/WaitGroup. - Races: any shared map or slice written from two goroutines; mutex values copied by value;
go test -raceis not optional. - HTTP clients:
http.DefaultClienthas no timeout. SetTimeoutor use per-request contexts. Alwaysdefer resp.Body.Close()and drain the body to reuse connections. - Servers: set
ReadHeaderTimeout,ReadTimeout,WriteTimeout,IdleTimeout; shut down withsignal.NotifyContext+srv.Shutdown(ctx); recover panics per request, never globally swallow them. - Database:
rows.Close()and checkrows.Err(); passctxto every query; one transaction per unit of work withdefer tx.Rollback(); pool sizing against the DB'smax_connections. - NULL in old rows: a scan into a plain
string,int64ortime.Timefails at run time. Usepgtypeorsql.Null*types for nullable columns, and test with a NULL row. - Transaction retries: Postgres can abort a transaction with SQLSTATE 40001 (serialization failure) or 40P01 (deadlock). Retry the whole transaction a set number of times. Anything sent outside the database inside it, such as a call or an email, runs again on retry, so keep those out.
- Nil interfaces: a nil
*Tstored in an interface is notnil. Returnnilexplicitly. - Slices:
appendon a sub-slice can overwrite the parent; copy when handing out slices of internal state. - Errors: never
err != nilthen continue with the zero value; neverpanicfor expected failures; sentinel errors exported, wrapped with context at each layer, translated to HTTP status at the edge only. init()doing I/O or reading env is a testability bug; wire inmain.- JSON: unexported fields are silent no-ops;
omitemptyon structs does nothing; usejson.RawMessagefor pass-through payloads. - sqlc/pgx: Postgres
intervalmaps topgtype.Interval, nottime.Duration;numericneedspgtype.Numericorshopspring/decimal; nullable columns becomepgtype.Textetc. Do the conversion in one place. - Time: store UTC, convert at the edge;
time.Now()in business logic makes tests flaky — inject a clock. - Request context ends when the handler returns: a goroutine or job started from a handler needs
context.WithoutCancel(Go 1.21+) and its own stop signal.
Service structure that scales
main.gowires config, logger, DB, HTTP; no business logic.- Config from env with validation at startup (fail fast, print which key is missing, never the value).
log/slogstructured logging with request id, trace id, and no PII; one logger passed down, not a global.- Middleware order: request id → recover → timeout → auth → handler. Health (
/healthzliveness,/readyzchecks DB) unauthenticated. - Workers:
errgroup.WithContext, bounded concurrency (semaphore or worker pool), idempotent jobs, retries with jitter, and a dead-letter path. - Rolling deploys run old and new binaries at once. A job queued by new code can reach an old worker, and the reverse, so version the job payload. A worker that meets a job type it does not know retries it or sends it to the dead-letter path; it never drops it. On SIGTERM, stop taking work, and finish or re-queue in-flight jobs before the platform's stop timeout.
- Outbox pattern for "write DB and publish event" to avoid dual-write loss.
Testing
- Table-driven tests with
t.Runandt.Parallel()where safe; name cases by behavior. httptestfor handlers;testcontainers-goor a Docker-provided Postgres for repositories (not sqlite substitutes); golden files for serialized output.go test -race -count=1 ./...in CI;-shuffle=onto catch order dependence; fuzz tests for parsers and decoders.- Benchmarks with
b.ReportAllocs(); compare withbenchstatbefore claiming a speedup. - Decode real production payloads, or a sanitized copy, through the new code, not only hand-written fixtures. Include a NULL row, and a number that arrives as a string, which a hand-typed fixture often lacks.
- Walk the scenarios in the shared bar, section 3, and name any case left untested, especially concurrent callers with retries and a context cancelled mid-call.
Performance
- Profile before optimizing:
net/http/pprofin non-public listeners,go tool pproffor cpu, heap, mutex, block, goroutine. go build -gcflags=-mshows escapes; preallocate slices with known length;strings.Builder;sync.Poolonly for measured hot buffers.- In containers set
GOMEMLIMITand useautomaxprocs(or Go 1.25+ container-awareGOMAXPROCS) so the runtime respects cgroup limits.
Production build
CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -trimpath -ldflags="-s -w -X main.version=$(git rev-parse --short HEAD)" -o bin/app ./cmd/app
Distroless or scratch base with CA certs and tzdata; non-root user; one binary per image.
Verification
gofmt -l . && go vet ./...
golangci-lint run # or staticcheck ./...
go test -race -count=1 ./...
govulncheck ./...
Guardrails
- Do not add a framework, ORM, or DI container to a codebase that already runs fine on the standard library.
- Do not ignore returned errors (including
Close,Write,Flush) to quiet the linter. - Do not share
*sql.Txorpgx.Txacross goroutines. - Do not claim concurrency-safe without a race-detector run.
- Do not put secrets in flags or build args; env or a secrets manager only.
Output format
Go version: [x.y] (latest stable [x.y], checked [date]) - Layout: [cmd/internal] - Framework: [net/http | Echo | Chi | Gin | gRPC]
Tooling honored: [linters, sqlc, migrations, CI]
Findings:
P0/P1/P2 - [file:line] - [issue] - [fix]
Change plan: [smallest correct change]
Verification: [commands run and result; race detector status]
References
../../references/checklists/go-development-checklist.md../../references/checklists/api-design-checklist.md../../references/checklists/database-engineering-checklist.md../../references/checklists/engineering-quality-bar.md
Extra idioms and test habits
- Functional options:
type Option func(*Server)withWithTimeout(...)style constructors and sensible defaults set before applying options, instead of long config parameter lists. - Style traps: naked returns in long functions;
panicfor control flow;context.Contextstored in a struct; mixing value and pointer receivers on one type (pick one); package-levelvar dbset ininit()(inject through a constructor instead); embedding a type just to borrow its methods when a named field would be clearer. - Leak-safe producer: if a goroutine sends on a channel, use a buffered channel of 1 or
selectonctx.Done()so it cannot block forever when the receiver is gone. - Linters worth enabling in golangci: errcheck with
check-type-assertions, govet withshadow, staticcheck, ineffassign, unused, misspell, unconvert, unparam. - Test helpers: call
t.Helper(), register teardown witht.Cleanup(), uset.TempDir()for files, and use tiny generic assert helpers sparingly. Nevertime.Sleepin tests; wait on a channel or condition. Test behavior through the public API, not private functions. Mock at interface boundaries but prefer real integration tests where cheap. - Flaky hunt:
go test -count=10 ./...(plus-raceand-shuffle=on); fix or delete flaky tests, do not ignore them. - Coverage as a signal only: roughly 100% for critical business logic, 90%+ for public APIs, 80%+ elsewhere, generated code excluded; use
go tool cover -functo find untested branches rather than chasing the number.
Adapted in part from ECC skills/golang-patterns and skills/golang-testing (affaan-m/ECC, MIT). The ECC testing example that uses in-memory sqlite as a database test helper was not adopted; use a real Postgres as above.