Build useful CLIs, safe cloud automation, and a Kubernetes operator. From your first Go module to production behavior, with a lab in every chapter.
← → / Space: navigate · I: contents · O: overview · T: theme · F: fullscreen
Select a chapter · press I anywhere to return here
Concepts to understand and explain before the lab.
Platform use cases: CLIs, API adapters, inventory and diagnostic tools, and Kubernetes controllers.
The trade-off: a compiled binary and strong standard library versus a scripting language; choose Go when distribution, concurrency, or long-running services justify it.
Map the two projects used throughout: platformctl (read-only CLI) and PlatformEnvironment (local Kubernetes operator).
A focused fragment or decision pattern. Try it, then change one condition.
One-time text transform → Bash/Python
Portable team CLI → Go
Continuous desired-state loop → Go controllerUse Go for a durable product boundary, not just because a task is technical.
Concepts to understand and explain before the lab.
Install Go, verify go version and go env; configure editor support with gopls.
Create a module with go mod init; run a program with go run; build with go build.
Use a local kind cluster for Kubernetes labs; reserve AWS labs for a sandbox or recorded fixtures.
A focused fragment or decision pattern. Try it, then change one condition.
mkdir platformctl && cd platformctl
go mod init example.com/platformctl
cat > main.go <<'EOF'
package main
import "fmt"
func main() { fmt.Println("hello platform") }
EOF
go run . && go build .The module path identifies imports; it does not need a public repository for a local lab.
Concepts to understand and explain before the lab.
For each concept: read a small example, predict its behavior, run it, change one input, then explain the result.
Track an error log of compiler errors, failed tests, and their fixes; use the Go docs before relying on snippets.
Lab 0: create the repository skeleton and a hello platform command; verify a clean build and test run.
A focused fragment or decision pattern. Try it, then change one condition.
Predict → Run → Change one input → Explain
go test ./...
go doc context.Context
go help modType examples yourself, then compare the actual output with your prediction.
Open each question only after you have answered it aloud.
When a portable, tested, long-lived tool or controller justifies a compiled binary.
Its module path in go.mod.
Locally; AWS reads use fixtures or a sandbox, Kubernetes writes use a separate kind cluster.
Complete this before starting the next chapter.
Install Go and confirm go version and go env.
Create platformctl with go mod init and a cmd/platformctl entry point.
Print hello platform; run, build, format, and test it.
go build ./... and go test ./... pass.Concepts to understand and explain before the lab.
package main, imports, exported names, main, comments, and the Go formatting convention.
Variables, const, zero values, short declarations, basic numeric and string types, explicit conversions.
Value semantics, pointers, nil, addressability, and when a pointer is needed.
A focused fragment or decision pattern. Try it, then change one condition.
type Health struct { Ready bool; Restarts int }
var h Health // false, 0
func markReady(h *Health) { h.Ready = true }Use a pointer when mutation or absence matters; do not use one merely to avoid a tiny copy.
Concepts to understand and explain before the lab.
if, switch, for, range, defer, and early returns; no exception-based control flow.
Go 1.22 per-iteration loop variables (when the module's language version is at least 1.22) and range over integers; Go 1.23 range over iterator functions and the iter package.
Scope and shadowing, including accidental err shadowing; labeled loops only when justified.
Time and duration values for retries and timeouts.
A focused fragment or decision pattern. Try it, then change one condition.
for i := range 3 { fmt.Println(i) } // 0, 1, 2
for _, name := range names { go func() { use(name) }() }
for name := range slices.Values(names) { fmt.Println(name) } // Go 1.23Per-iteration variables require a module language version of Go 1.22 or newer; review old modules carefully.
Concepts to understand and explain before the lab.
Arrays versus slices; length, capacity, append, shared backing arrays, copying, and mutation hazards.
Maps: lookup with the ok idiom, missing keys, iteration order, and safe initialization.
Strings as UTF-8 bytes; runes versus bytes; safe traversal and normalization boundaries.
A focused fragment or decision pattern. Try it, then change one condition.
a := []string{"dev", "prod"}
b := a[:1]
b[0] = "test" // a[0] is now test
c := append([]string(nil), a...) // independent copySlices are descriptors over backing arrays. Use a copy when ownership must be independent.
Concepts to understand and explain before the lab.
Parse a line-oriented list of service names, validate names, deduplicate, and print sorted results.
Compare stdout output with stderr diagnostics and use a nonzero exit on invalid input.
Lab 1: implement platformctl services list using only the standard library.
A focused fragment or decision pattern. Try it, then change one condition.
seen := map[string]struct{}{}
for _, name := range input { seen[name] = struct{}{} }
for name := range seen { names = append(names, name) }
slices.Sort(names)Map iteration order is unspecified. Sort before producing human or machine-readable output.
Open each question only after you have answered it aloud.
The initialized value of a variable without an explicit assignment.
Go map iteration order is unspecified.
New loop variables are created per iteration for modules using the Go 1.22 language version.
Complete this before starting the next chapter.
Read service names from a fixture file with bounded input.
Reject empty or malformed names, deduplicate, then sort.
Print results on stdout and diagnostics on stderr.
Concepts to understand and explain before the lab.
Define structs for cluster, service, and health data; fields, tags, embedded structs, and methods.
Pointer versus value receivers; copying structs with slices/maps; keep state ownership explicit.
Separate input, domain, and output types instead of using one struct everywhere.
A focused fragment or decision pattern. Try it, then change one condition.
type Service struct { Name string; Ready bool }
type ServiceJSON struct { Name string `json:"name"`; Ready bool `json:"ready"` }Do not let an external API shape every internal type; translate at the boundary.
Concepts to understand and explain before the lab.
encoding/json: exported fields, tags, omitempty versus Go 1.24 omitzero, decoding, encoding, and unknown fields.
Distinguish absent, zero, and null when config or API contracts require it.
Bound input size; validate parsed data; never treat successful decoding as validation.
A focused fragment or decision pattern. Try it, then change one condition.
type Request struct { Replicas *int `json:"replicas,omitempty"` }
// nil = omitted; pointer to 0 = explicitly zero
type Report struct { SeenAt time.Time `json:"seenAt,omitzero"` }Use a pointer or explicit optional type when zero and missing mean different things.
Concepts to understand and explain before the lab.
Read line-oriented files with bufio; handle scanner limits and malformed records.
Go has no YAML package in the standard library; use sigs.k8s.io/yaml for the Kubernetes/config use case, with validation after conversion.
Use typed Kubernetes objects or validated schemas instead of editing YAML as strings.
A focused fragment or decision pattern. Try it, then change one condition.
raw, err := os.ReadFile(path)
if err != nil { return err }
jsonBytes, err := yaml.YAMLToJSONStrict(raw)
if err != nil { return fmt.Errorf("invalid YAML: %w", err) }Convert only at the boundary, then decode into a typed schema and validate semantics.
Concepts to understand and explain before the lab.
Define a stable JSON schema for a service inventory report; preserve field names and predictable ordering.
Lab 2: load fixture data and emit both human-readable text and machine-readable JSON; add invalid-input cases.
A focused fragment or decision pattern. Try it, then change one condition.
{"account":"111122223333","region":"us-east-1","services":[...]}Document field names and ordering before scripts depend on the output.
Open each question only after you have answered it aloud.
When absent and explicitly zero have different meanings.
No; validate domain constraints after parsing.
It bypasses structure and schema validation.
Complete this before starting the next chapter.
Define typed input and output structs with JSON tags.
Parse valid and invalid fixtures; validate semantics after decoding.
Emit stable text and JSON representations.
Concepts to understand and explain before the lab.
Multiple return values, variadic functions, closures, defer, and small functions with one clear job.
Pass dependencies explicitly; avoid package globals and hidden initialization.
Design package APIs around a caller's task, not a large generic framework.
A focused fragment or decision pattern. Try it, then change one condition.
type Store interface { List(context.Context) ([]Service, error) }
func Report(ctx context.Context, store Store) error {
services, err := store.List(ctx)
if err != nil { return err }; return render(services)
}Pass a narrow dependency from main into the operation; avoid package globals.
Concepts to understand and explain before the lab.
Return errors with context using %w; distinguish errors.Is, errors.As, errors.Join, and direct comparison.
Sentinel versus typed errors; translate low-level errors at boundaries without losing the cause.
Decide when to retry, report, or terminate; avoid logging and returning the same error at every layer.
A focused fragment or decision pattern. Try it, then change one condition.
if err != nil { return fmt.Errorf("list services in %s: %w", region, err) }
if errors.Is(err, context.DeadlineExceeded) { /* timeout */ }
var apiErr *smithy.GenericAPIError
if errors.As(err, &apiErr) { /* inspect code */ }
return errors.Join(collectErr, writeErr) // independent failuresA useful error says what failed while preserving the cause for callers.
Concepts to understand and explain before the lab.
Implicit interface implementation; small consumer-owned interfaces for test seams.
Type assertions and type switches; any only where a real boundary requires it.
Basic type parameters and constraints; use generics for repeated algorithms, not to hide concrete domain types.
A focused fragment or decision pattern. Try it, then change one condition.
type Clock interface { Now() time.Time }
// Better: define the interface where the caller needs it.
func Expired(now time.Time, deadline time.Time) bool { return !now.Before(deadline) }Prefer a plain value or function when an interface adds no useful substitution.
Concepts to understand and explain before the lab.
cmd/ for entry points and task-oriented internal packages; when internal/ helps.
Avoid circular imports and the utils dumping ground; document exported APIs.
Lab 3: refactor the inventory command into a loader, domain model, formatter, and CLI; verify errors preserve causes.
A focused fragment or decision pattern. Try it, then change one condition.
cmd/platformctl/main.go
internal/inventory/collect.go
internal/report/format.go
internal/config/load.goPackages should follow tasks and ownership, not a generic utils bucket.
Open each question only after you have answered it aloud.
It adds context while preserving the underlying error for Is/As.
Usually the consumer that needs the dependency boundary.
When multiple independent errors must be reported together.
Complete this before starting the next chapter.
Move loading, domain rules, and formatting into task-oriented packages.
Inject the loader into the report operation through a small interface.
Wrap errors with %w and assert errors.Is or errors.As.
Concepts to understand and explain before the lab.
go.mod, go.sum, semantic versions, go get, go mod tidy, and reproducible dependency review.
Module path and major-version suffixes; use go work for local multi-module development only when needed.
Go 1.24 tool directives and go tool for executable dependencies such as controller-gen; GOPRIVATE/GOPROXY for internal modules.
Dependency risk: direct versus transitive dependencies, updates, licenses, and vulnerability checks.
A focused fragment or decision pattern. Try it, then change one condition.
go mod tidy
go list -m all
go mod graph
go get example.com/dependency@v1.2.3Review why a dependency entered the graph before accepting a major update.
Concepts to understand and explain before the lab.
gofmt, go vet, go test, go doc, gopls, and a linter such as Staticcheck or golangci-lint as feedback rather than ritual.
Install govulncheck separately; it is not bundled with the Go toolchain.
Read compiler and vet output; use go list and go env to troubleshoot the build environment.
A focused fragment or decision pattern. Try it, then change one condition.
go fmt ./...
go vet ./...
go test ./...
govulncheck ./...Install govulncheck separately; pin it as a tool dependency where reproducibility matters.
Concepts to understand and explain before the lab.
go build versus go install; GOOS/GOARCH, build tags, and CGO trade-offs. Use CGO_ENABLED=0 for a static build only when dependencies permit; verify the binary.
Binary version information, reproducible build inputs, and why a container image should carry the binary's provenance.
A focused fragment or decision pattern. Try it, then change one condition.
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o dist/platformctl ./cmd/platformctl
file dist/platformctlA static build depends on your packages and linker choices; inspect the artifact instead of assuming.
Concepts to understand and explain before the lab.
Add a small dependency, update it, inspect the module graph, and remove it cleanly.
Lab 4: add format/test/vet/vulnerability checks to a local build script; explain each failure before fixing it.
A focused fragment or decision pattern. Try it, then change one condition.
go get -tool sigs.k8s.io/controller-tools/cmd/controller-gen@<version>
go tool controller-gen --helpThe Go 1.24 tool directive tracks an executable dependency in go.mod.
Open each question only after you have answered it aloud.
No; install and track it separately.
Aligns module requirements and checksums with imported packages.
Not unconditionally; dependencies and linker choices still require verification.
Complete this before starting the next chapter.
Track required tools with go.mod tool directives when supported.
Run format, vet, tests, a linter, and govulncheck.
Add a dependency, inspect the module graph, then remove it cleanly.
Concepts to understand and explain before the lab.
os, io, bufio, and filepath; readers and writers; safe file permissions.
Atomic output: write a temporary file, sync where appropriate, then rename; avoid partially written reports.
Bound reads and close resources; treat file paths as untrusted input. Use Go 1.24 os.Root/os.OpenRoot for directory-confined access when accepting relative paths.
A focused fragment or decision pattern. Try it, then change one condition.
f, err := os.CreateTemp(dir, "report-*")
// write, Sync, Close, then os.Rename to destination
// remove temp file on every error pathA report should be old or new, never half written. Consider filesystem sync requirements.
Concepts to understand and explain before the lab.
os/exec with argument arrays, context cancellation, exit status, and bounded output.
Why passing unsanitized input through a shell is dangerous; prefer APIs over shelling out when available.
Distinguish a child-process timeout from an application error.
A focused fragment or decision pattern. Try it, then change one condition.
cmd := exec.CommandContext(ctx, "kubectl", "get", "pods", "-n", namespace)
out, err := cmd.CombinedOutput()Argument arrays avoid shell interpretation. Bound output and report exit status.
Concepts to understand and explain before the lab.
Precedence: flags, environment, config file, defaults; validate once at startup.
Do not embed credentials or print secret values; use workload identity and SDK credential chains.
Redact sensitive fields in logs, errors, and diagnostic output.
A focused fragment or decision pattern. Try it, then change one condition.
flags > environment > config file > defaults
validate(config) once at startup
log only redacted configA config value's source matters when debugging behavior across environments.
Concepts to understand and explain before the lab.
Handle SIGINT/SIGTERM with signal.NotifyContext; exit cleanly and flush output.
Lab 5: implement config loading and atomic report output; test cancellation and invalid paths.
A focused fragment or decision pattern. Try it, then change one condition.
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
if err := run(ctx); err != nil { return err }Propagate the canceled context into child work, not just the outer loop.
Open each question only after you have answered it aloud.
To avoid exposing a partially written destination.
As a program and argument array, not interpolated shell text.
Directory-confined access, including paths that would escape through symlinks.
Complete this before starting the next chapter.
Implement flag > environment > file > default precedence.
Validate values once; redact sensitive diagnostics.
Write reports through a temporary file and rename on success; cancel a child process.
Concepts to understand and explain before the lab.
Launch and join work; buffered versus unbuffered channels; close ownership and select.
A goroutine is not free: prevent leaks, blocked sends, and unbounded fan-out.
A focused fragment or decision pattern. Try it, then change one condition.
jobs := make(chan Job)
go func() { defer close(jobs); for _, j := range input { jobs <- j } }()
for j := range jobs { process(j) }The sender owns closing. Add context-aware sends and receives in real workers.
Concepts to understand and explain before the lab.
sync.Mutex, sync.RWMutex, sync.WaitGroup, Go 1.25 WaitGroup.Go, and when channels simplify ownership.
Race conditions, data races, and how go test -race helps detect the latter.
The Go memory model: happens-before relationships, synchronization, and why an apparently working concurrent program can still be incorrect.
Avoid concurrent map writes and copying mutexes.
A focused fragment or decision pattern. Try it, then change one condition.
var mu sync.Mutex
mu.Lock(); count++; mu.Unlock()
// A mutex unlock happens before a later lock of that mutex.
go test -race ./...A program that appears to work may still have a race; synchronization defines correctness.
Concepts to understand and explain before the lab.
Pass context.Context as the first parameter; deadlines, cancellation, and request-scoped values.
Never store a context in a struct for convenience; propagate it into AWS, Kubernetes, HTTP, and child-process calls.
Distinguish cancellation from timeout for user-facing errors.
A focused fragment or decision pattern. Try it, then change one condition.
ctx, cancel := context.WithTimeout(parent, 5*time.Second)
defer cancel()
resp, err := client.Do(req.WithContext(ctx))Pass context first and never store it inside a long-lived struct for convenience.
Concepts to understand and explain before the lab.
Worker pools, semaphores, errgroup.WithContext with SetLimit, golang.org/x/time/rate, backpressure, retry budgets, and jitter.
Decide what can run in parallel without increasing API throttling or cost.
A focused fragment or decision pattern. Try it, then change one condition.
g, ctx := errgroup.WithContext(ctx)
g.SetLimit(5)
for _, item := range items { item := item; g.Go(func() error { return fetch(ctx, item) }) }
return g.Wait()Limit concurrency before API throttling or memory pressure becomes the limiter.
Concepts to understand and explain before the lab.
Lab 6: query multiple fixture services concurrently with a fixed worker limit; prove cancellation stops all workers and -race stays clean.
A focused fragment or decision pattern. Try it, then change one condition.
start 20 fixture requests with limit 4
cancel after first result
assert active workers return to zero
go test -race ./...A cancellation test should prove no worker stays blocked, not just that one error is returned.
Open each question only after you have answered it aloud.
Operations that receive and observe the context; it does not forcibly stop arbitrary goroutines.
Error propagation and cancellation through a derived context.
Synchronization and happens-before relations between concurrent operations.
Complete this before starting the next chapter.
Create 20 fixture requests with errgroup.WithContext and SetLimit(4).
Cancel the context mid-run; ensure every worker returns.
Run the race detector and a rate-limit test.
go test -race passes.Concepts to understand and explain before the lab.
Reuse http.Client; set timeouts; create requests with context; close and bound response bodies.
For HTTP/1 connection reuse, read a response to EOF when consuming it; if discarding it, use a bounded drain on Go 1.26 and earlier when reuse matters. Go 1.27 adds automatic bounded draining of unread bodies. Always close the body.
Inspect status codes, headers, and content types before decoding; retry only safe/idempotent operations.
TLS verification, proxy behavior, and why disabling certificate checks is not a fix.
A focused fragment or decision pattern. Try it, then change one condition.
req, _ := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
resp, err := client.Do(req)
if err != nil { return err }
defer resp.Body.Close()
body, err := io.ReadAll(io.LimitReader(resp.Body, maxBytes))Bound response size. Close every body; understand HTTP/1 reuse behavior for the Go version you ship.
Concepts to understand and explain before the lab.
net/http handlers, Go 1.22 ServeMux method/wildcard patterns, middleware, request IDs, input limits, ReadHeaderTimeout, and graceful shutdown.
Separate transport DTOs from domain logic; validate and return consistent error responses.
A focused fragment or decision pattern. Try it, then change one condition.
mux := http.NewServeMux()
mux.HandleFunc("GET /healthz", health)
mux.HandleFunc("GET /services/{name}", showService)
server := &http.Server{Handler: mux, ReadHeaderTimeout: 5*time.Second}Method and wildcard patterns require Go 1.22+; bound headers and bodies.
Concepts to understand and explain before the lab.
Idempotency, pagination, conditional requests, exponential backoff with jitter, and rate-limit handling.
Use explicit deadlines and per-call error context to make failures diagnosable.
A focused fragment or decision pattern. Try it, then change one condition.
if status == 429 || status >= 500 {
wait := backoff(attempt) + jitter()
if err := sleepContext(ctx, wait); err != nil { return err }
}Retry only safe operations, honor Retry-After when present, and stop at a deadline.
Concepts to understand and explain before the lab.
Explain bearer tokens, service identity, and why credentials should be supplied by the runtime.
Avoid logging authorization headers; test redaction and error paths.
A focused fragment or decision pattern. Try it, then change one condition.
token := os.Getenv("API_TOKEN")
req.Header.Set("Authorization", "Bearer "+token)
// Never log req.Header or token.Prefer workload identity and short-lived tokens over static environment secrets in production.
Concepts to understand and explain before the lab.
Lab 7: build a small HTTP health aggregator against local test servers; include timeout, malformed JSON, 429, and 5xx cases.
A focused fragment or decision pattern. Try it, then change one condition.
httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusTooManyRequests)
}))Test timeout, 429, 5xx, malformed JSON, and cancellation without calling a public API.
Open each question only after you have answered it aloud.
Its transport can reuse connections and is safe for concurrent use.
To bound time spent receiving request headers.
No; consider idempotency, deadline, rate limits, and Retry-After.
Complete this before starting the next chapter.
Serve local healthy, slow, malformed, 429, and 5xx responses with httptest.
Use one reusable client with request contexts, timeouts, bounded bodies, and status checks.
Emit a report that separates unavailable from unhealthy.
Concepts to understand and explain before the lab.
Start with flag; introduce Cobra for a real command tree, help generation, and shared flags.
Commands should describe operations (inspect, report, validate), not expose internal package names.
Make read-only the default; put any future write action behind an explicit command and dry-run option.
A focused fragment or decision pattern. Try it, then change one condition.
platformctl services list --output=json
platformctl services inspect api --timeout=5s
platformctl versionBegin with stdlib flag; add Cobra when nested commands and help become real needs.
Concepts to understand and explain before the lab.
Human output versus stable JSON; stdout for data, stderr for diagnostics, useful exit codes.
Flags for context, namespace, region, profile, timeout, and output format; validate conflicting flags.
Avoid surprise prompts in automation; provide --help, examples, and a version command.
A focused fragment or decision pattern. Try it, then change one condition.
stdout: report data only
stderr: diagnostics and warnings
0: success · 2: invalid usage · 3: partial collection · 4: upstream failureDocument exit codes so shell automation can act without parsing prose.
Concepts to understand and explain before the lab.
Progress only on terminals; no color in redirected output; avoid leaking secrets in debug mode.
Show the target account/cluster before any mutating action; require explicit scope in multi-account tools.
A focused fragment or decision pattern. Try it, then change one condition.
Target: account 111122223333 / region us-east-1
Mode: read-only
Command: inventoryAn operator should see the exact target before any future write mode is introduced.
Concepts to understand and explain before the lab.
Lab 8: turn platformctl into a command tree with services list, services inspect, and version; snapshot the JSON contract and exit codes.
A focused fragment or decision pattern. Try it, then change one condition.
platformctl services list --output=json | jq -e '.services | type == "array"'
platformctl --help
platformctl versionA CLI is an interface: test its output and behavior, not just internal functions.
Open each question only after you have answered it aloud.
Machine- or human-readable result data only.
Automation can respond without parsing prose.
Read-only behavior with explicit target scope.
Complete this before starting the next chapter.
Add services list, services inspect, and version commands.
Support --output=json, --timeout, and clear help examples.
Document stdout/stderr and exit-code behavior.
Concepts to understand and explain before the lab.
Table-driven tests, subtests, test helpers, golden files where output is intentionally stable.
Test observable behavior and failure paths; avoid tests that merely mirror implementation.
A focused fragment or decision pattern. Try it, then change one condition.
tests := []struct{ in string; want bool }{{"api", true}, {"", false}}
for _, tt := range tests { t.Run(tt.in, func(t *testing.T) {
if got := valid(tt.in); got != tt.want { t.Fatalf("got %v", got) }
}) }Test one behavior across normal and edge cases; name failures clearly.
Concepts to understand and explain before the lab.
Inject clocks, HTTP transports, AWS/Kubernetes client interfaces, and filesystem access where it improves isolation.
Use Go 1.24 t.Context() for test-scoped cancellation and Go 1.25 testing/synctest for deterministic time and concurrency tests without real sleeps.
Use httptest for local HTTP integration; use fakes only for behavior they model accurately.
A focused fragment or decision pattern. Try it, then change one condition.
synctest.Test(t, func(t *testing.T) {
ctx, cancel := context.WithTimeout(t.Context(), time.Second)
defer cancel()
<-ctx.Done() // virtual time advances
})Go 1.25 synctest makes timing tests deterministic; avoid real sleeps in unit tests.
Concepts to understand and explain before the lab.
Race detector, fuzz tests for parsers, coverage as a gap finder rather than a target.
Benchmarks for actual bottlenecks with Go 1.24 b.Loop(); compare allocations and wall time before optimizing.
A focused fragment or decision pattern. Try it, then change one condition.
func FuzzParseReport(f *testing.F) {
f.Add([]byte(`{"services":[]}`))
f.Fuzz(func(t *testing.T, data []byte) { _, _ = ParseReport(data) })
}A fuzz target should also assert useful invariants, not merely avoid panics.
Concepts to understand and explain before the lab.
Read stack traces; use go test -v, go tool pprof, runtime traces, and net/http/pprof only on protected endpoints.
Diagnose memory growth, blocked goroutines, excessive allocations, and API fan-out.
A focused fragment or decision pattern. Try it, then change one condition.
go test -bench=. -benchmem ./internal/report
go test -cpuprofile=cpu.out ./internal/report
go tool pprof cpu.outRecord a baseline and explain the bottleneck before changing allocations or concurrency.
Concepts to understand and explain before the lab.
Lab 9: add a failing fixture, a fuzz target for a report parser, a race regression test, and a benchmark; document the observed fix.
A focused fragment or decision pattern. Try it, then change one condition.
1. Save the failing input.
2. Add a test that fails before the fix.
3. Fix the code.
4. Run unit, race, fuzz seed, benchmark.A reported fix needs evidence that the original failure cannot recur.
Open each question only after you have answered it aloud.
The original failure is reproduced before and prevented after the fix.
It virtualizes time for deterministic concurrency and timeout tests.
Finding untested behavior, not maximizing a number by itself.
Complete this before starting the next chapter.
Save a failing parser input and write a regression test.
Add a fuzz target with a useful invariant and run seed cases.
Benchmark before and after the fix; profile only if a bottleneck appears.
Concepts to understand and explain before the lab.
Use config.LoadDefaultConfig, a named profile or workload role, and an explicit region.
Understand the credential chain; do not hard-code keys or assume the active AWS account.
Check caller identity and target scope before reporting or changing resources.
A focused fragment or decision pattern. Try it, then change one condition.
cfg, err := config.LoadDefaultConfig(ctx, config.WithRegion(region))
if err != nil { return err }
stsClient := sts.NewFromConfig(cfg)Resolve account identity before collecting data; never print the credential chain.
Concepts to understand and explain before the lab.
Construct service clients from shared config; pass context to every operation.
Understand typed inputs/outputs, pointer helpers, pagination, waiters, and API error types.
Use bounded concurrency and account for AWS API throttling.
A focused fragment or decision pattern. Try it, then change one condition.
p := ecs.NewListServicesPaginator(client, &ecs.ListServicesInput{Cluster: &cluster})
for p.HasMorePages() {
page, err := p.NextPage(ctx)
if err != nil { return err }
arns = append(arns, page.ServiceArns...)
}One API response is often only the first page. Handle access denied and throttling separately.
Concepts to understand and explain before the lab.
Collect ECS services, ALBs, and CloudWatch alarms as a read-only example.
Normalize identifiers, include region/account in every record, and distinguish missing permission from missing resource.
Produce JSON and text reports with timestamps and partial-failure summaries.
A focused fragment or decision pattern. Try it, then change one condition.
type Record struct { Account, Region, ARN, Health string }
// Include account and region in every record.
// Keep collection errors separate from empty results.A missing resource and a failed read are different findings.
Concepts to understand and explain before the lab.
SDK retry defaults versus application retries; avoid duplicate retries and non-idempotent writes.
Set deadlines, handle pagination fully, and cap requests; state when an AWS API can incur cost.
A focused fragment or decision pattern. Try it, then change one condition.
read-only ≠ free
API throttling ≠ retry immediately
partial data ≠ healthy empty environmentSome AWS APIs bill per request; declare cost and rate limits before a large scan.
Concepts to understand and explain before the lab.
Lab 10: add platformctl aws inventory against a sandbox or recorded SDK fixtures; verify account/region, pagination, access-denied handling, and no write API calls.
A focused fragment or decision pattern. Try it, then change one condition.
platformctl aws inventory --account 111122223333 --region us-east-1
# Run against recorded responses first, sandbox second.Verify account and region from STS; test pagination and AccessDenied without writes.
Open each question only after you have answered it aloud.
To verify the AWS account actually selected by the credential chain.
The inventory silently misses resources.
No; some AWS APIs charge per request.
Complete this before starting the next chapter.
Start with recorded SDK responses, then use a sandbox profile if available.
Check STS account identity and explicit region; paginate ECS service results.
Report partial failures and AccessDenied without attempting writes.
Concepts to understand and explain before the lab.
Group/version/kind, namespaced versus cluster-scoped resources, metadata, resourceVersion, and optimistic concurrency.
Desired state versus observed state; spec, status, and conditions.
A focused fragment or decision pattern. Try it, then change one condition.
metadata.generation: desired-spec revision
status.observedGeneration: revision reconciled
metadata.resourceVersion: optimistic concurrency tokenDo not confuse generation with resourceVersion; they answer different questions.
Concepts to understand and explain before the lab.
Local kubeconfig versus in-cluster ServiceAccount credentials; never embed a kubeconfig in the binary.
Typed client-go clients, REST config, timeouts, user agent, and rate limits.
RBAC: discover exactly which verbs and resources a tool needs.
A focused fragment or decision pattern. Try it, then change one condition.
cfg, err := clientcmd.BuildConfigFromFlags("", kubeconfig)
// In a Pod, use rest.InClusterConfig().
// Scope permissions with RBAC, not a hidden CLI flag.Local kubeconfig and in-cluster ServiceAccount credentials are different auth paths.
Concepts to understand and explain before the lab.
Get, list, create, patch, update, delete; label/field selectors and pagination.
Handle NotFound, Conflict, Forbidden, and transient failures distinctly; use retry-on-conflict only around fresh reads.
Server-side apply and field ownership at a conceptual level; avoid blind full-object updates.
A focused fragment or decision pattern. Try it, then change one condition.
retry.RetryOnConflict(retry.DefaultRetry, func() error {
current, err := client.Get(ctx, name, metav1.GetOptions{})
if err != nil { return err }
mutate(current)
_, err = client.Update(ctx, current, metav1.UpdateOptions{})
return err
})Read a fresh object inside every retry; never re-send an old resourceVersion.
Concepts to understand and explain before the lab.
Watch events and resourceVersion expiration; why informers/cache are preferred for long-running controllers.
Dynamic client and discovery for unknown resource types; use typed clients when schemas are known.
A focused fragment or decision pattern. Try it, then change one condition.
watch from resourceVersion → receive events
if watch expires (410 Gone): list again, capture new resourceVersion
for controllers: use informer/cache instead of a raw watchWatch streams are not a durable queue. Re-list when state may have been missed.
Concepts to understand and explain before the lab.
Lab 11: add platformctl k8s workloads to list Deployments and Pods in a named local namespace; show readiness, owner, and actionable errors. Run the CLI in a kind Pod under a least-privilege ServiceAccount, or run it locally with a temporary kubeconfig built from a short-lived kubectl create token token. Use kubectl --as=system:serviceaccount:<namespace>:<name> only to verify RBAC when the caller has impersonation permission.
A focused fragment or decision pattern. Try it, then change one condition.
kubectl create token platform-reader -n lab
# Build a temporary kubeconfig with token + cluster CA.
# Or run platformctl as a Pod using serviceAccountName: platform-reader.A local process does not inherit a Pod's ServiceAccount. Impersonation needs explicit permission.
Open each question only after you have answered it aloud.
It needs a temporary kubeconfig/token, or it must run as a Pod under that ServiceAccount.
After reading a fresh object inside the retry loop.
List again to establish current state and a new resourceVersion.
Complete this before starting the next chapter.
Create a platform-reader ServiceAccount and narrow Role in kind.
Run platformctl as a Pod under that account or use a short-lived token in a temporary kubeconfig.
List Pods and Deployments in one namespace; verify forbidden cross-namespace access.
Concepts to understand and explain before the lab.
Level-triggered reconciliation: repeatedly make actual state converge on desired state.
Idempotency, eventual consistency, at-least-once events, and why a controller must tolerate missing or stale objects.
Compare a one-shot CLI action with a continuous controller.
A focused fragment or decision pattern. Try it, then change one condition.
desired = read(PlatformEnvironment)
actual = read(Namespace, ResourceQuota)
if different: apply minimal change
update status; requeue only when neededA missed event must not break convergence: the next reconcile can recover from current state.
Concepts to understand and explain before the lab.
Define a cluster-scoped PlatformEnvironment that owns the Namespace it creates. Keep the spec small (namespace label set, quota, and optional config) and expose a status condition.
Schema, validation, defaults, versioning, and compatibility; avoid exposing unstable internal fields.
Explain why a cluster-scoped Namespace cannot have a namespaced owner. Document the operator's cluster-wide blast radius and refuse to adopt a pre-existing Namespace by accident.
A focused fragment or decision pattern. Try it, then change one condition.
PlatformEnvironment (cluster-scoped)
└── Namespace (cluster-scoped dependent)
└── ResourceQuota (namespaced dependent)A cluster-scoped Namespace cannot have a namespaced owner; refuse to adopt a pre-existing Namespace.
Concepts to understand and explain before the lab.
Scaffold API and controller; understand manager, cache, client, scheme, watches, predicates, and workqueue.
Reconcile request, fetch, compare, create/update, status update, and requeue decision.
Keep business logic separate from Kubernetes transport details.
A focused fragment or decision pattern. Try it, then change one condition.
func (r *Reconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
var env platformv1.PlatformEnvironment
if err := r.Get(ctx, req.NamespacedName, &env); err != nil {
return ctrl.Result{}, client.IgnoreNotFound(err)
}
return r.converge(ctx, &env)
}A controller-runtime manager supplies the cache, client, watches, and workqueue.
Concepts to understand and explain before the lab.
Owner references from the Namespace and namespaced dependents to the cluster-scoped PlatformEnvironment; garbage collection in a full cluster. Use finalizers when external or non-owned cleanup must finish first.
Deletion timestamp, idempotent cleanup, stuck finalizers, and how to recover safely.
A focused fragment or decision pattern. Try it, then change one condition.
Create Namespace with ownerReference → PlatformEnvironment UID
Use finalizer only for external or non-owned cleanup
Test actual GC in kind, not envtestOwner references are a deletion mechanism only when the owner/dependent scope is valid.
Concepts to understand and explain before the lab.
Conditions, observed generation, meaningful messages, and avoiding status update loops.
Leader election, retries, rate limits, and avoiding hot reconciliation loops.
A focused fragment or decision pattern. Try it, then change one condition.
condition: Ready=False, Reason=Creating
observedGeneration: 3
condition: Ready=True, Reason=AvailableUpdate status only when it changes; otherwise status writes can trigger hot loops.
Concepts to understand and explain before the lab.
Pure unit tests for decision logic; envtest for API-server behavior; kind tests for namespace-controller and garbage-collector behavior absent from envtest.
envtest can validate ownership metadata but cannot complete Namespace deletion: the Namespace stays Terminating without built-in controllers. Run delete/GC assertions in kind.
Test create, update, conflicts, invalid specs, missing RBAC, and restart convergence; test full deletion in kind.
A focused fragment or decision pattern. Try it, then change one condition.
unit: decide desired changes
envtest: API server, admission/defaulting, ownership metadata
kind: namespace controller, garbage collection, restartenvtest has no built-in controllers: Namespace deletion remains Terminating.
Concepts to understand and explain before the lab.
Lab 12: implement the cluster-scoped PlatformEnvironment in kind with a minimal ClusterRole; provision an owned Namespace and quota, update status, and verify deletion/garbage collection in kind. Use envtest for API and reconciliation checks, not Namespace deletion.
A focused fragment or decision pattern. Try it, then change one condition.
create PlatformEnvironment → observe Namespace + quota
update labels/quota → observe convergence
delete CR → observe cleanup in kindUse a dedicated kind cluster and a minimal ClusterRole; never point the lab at production.
Open each question only after you have answered it aloud.
It owns a Namespace, which is cluster-scoped.
Make actual state converge to desired state idempotently.
No; use kind because envtest lacks namespace and garbage-collection controllers.
Complete this before starting the next chapter.
Scaffold a cluster-scoped CRD and minimal ClusterRole in a dedicated kind cluster.
Reconcile an owned Namespace and ResourceQuota; update status and observed generation.
Test API logic with envtest; test create/update/delete and garbage collection in kind.
Concepts to understand and explain before the lab.
Structured logs with log/slog, request/reconcile IDs, useful metrics, and traces across API calls.
Health/readiness endpoints, error classification, cardinality limits, and secret redaction.
Use OpenTelemetry where traces clarify cross-service latency; avoid telemetry that cannot drive action.
A focused fragment or decision pattern. Try it, then change one condition.
slog.InfoContext(ctx, "reconcile complete", "name", env.Name, "duration", elapsed)
metric: reconcile_errors_total{reason="conflict"}
trace: API read → apply → statusAvoid high-cardinality labels such as resource UID or error text.
Concepts to understand and explain before the lab.
Graceful shutdown, bounded queues, memory/CPU limits, pprof access controls, and SIGTERM behavior.
GOMEMLIMIT as a memory-pressure control; Go 1.25 container-aware default GOMAXPROCS uses Linux cgroup CPU limits when not overridden.
Timeouts and connection reuse; understand how limits and probes interact during rollouts.
A focused fragment or decision pattern. Try it, then change one condition.
GOMEMLIMIT=700MiB
# Go 1.25+ default GOMAXPROCS considers cgroup CPU limits.
# Set explicit limits and measure throttling and GC pressure.GOMEMLIMIT is guidance to the runtime, not a hard container-memory limit.
Concepts to understand and explain before the lab.
Least-privilege RBAC/IAM, non-root container, pinned dependencies, vulnerability scanning, and signed releases.
Threat model untrusted config, API responses, and user input; never execute input as shell syntax.
A focused fragment or decision pattern. Try it, then change one condition.
ClusterRole: get/list/watch/update PlatformEnvironment; status/finalizers as needed
Namespace: get/list/watch/create/update/delete
ResourceQuota: get/list/watch/create/update/deleteScope each verb and resource; confirm generated RBAC against actual API calls.
Concepts to understand and explain before the lab.
Multi-stage Docker build, small runtime image, architecture targets, version/commit metadata, SBOM, and provenance.
CI checks: format, vet, unit/integration tests, race detector where supported, vulnerability scan, image build.
A focused fragment or decision pattern. Try it, then change one condition.
gofmt → vet → unit/integration → race → vuln scan
→ build Linux binary → image → SBOM/signature → deployA release should be traceable to source, dependencies, tests, and a unique artifact digest.
Concepts to understand and explain before the lab.
Lab 13: containerize the operator, add probes and metrics, deploy into kind with narrow RBAC, then rehearse shutdown and a failed reconciliation.
A focused fragment or decision pattern. Try it, then change one condition.
send SIGTERM during reconciliation
expect no new work, bounded exit time, and accurate status after restartA controller must recover from interruption because work may stop between any two API writes.
Open each question only after you have answered it aloud.
No; it guides runtime GC behavior.
Stop accepting work, let in-flight work finish within a deadline, and recover on restart.
Unbounded values such as resource names, UIDs, or raw error messages.
Complete this before starting the next chapter.
Build a small image and deploy with narrow RBAC, probes, and metrics.
Send SIGTERM during reconciliation; restart the controller.
Inspect logs, conditions, and resource ownership after recovery.
Concepts to understand and explain before the lab.
Deliver two connected artifacts: platformctl for read-only inventory and PlatformEnvironment for local self-service provisioning.
Draw data flow, identity boundaries, API permissions, retry behavior, and failure modes before implementation.
A focused fragment or decision pattern. Try it, then change one condition.
platformctl: human-triggered, read-only, short-lived
PlatformEnvironment: continuous, scoped writes, long-livedDraw identity and permission boundaries for both before implementation.
Concepts to understand and explain before the lab.
A new learner can clone, build, test, and run both artifacts from documented commands.
platformctl has stable JSON output, useful errors, cancellation, bounded concurrency, and no embedded credentials.
The operator converges after create/update/restart, reports status, handles deletion, and runs under least-privilege RBAC.
CI runs relevant checks; a release is traceable to a commit and dependency set.
A focused fragment or decision pattern. Try it, then change one condition.
clone → build → test → run
inspect JSON + exit codes
create/update/delete CR in kind
review CI evidence and image digestA new engineer should succeed from the repository guide alone.
Concepts to understand and explain before the lab.
Explain when Go is the right tool and when Bash, Python, Terraform, or an existing controller is simpler.
Review the most common failure patterns: nil dereference, slice aliasing, ignored errors, leaking goroutines, unbounded retries, stale cache reads, broad IAM/RBAC, and non-idempotent reconciliation.
Lab 14: demo both artifacts, run a failure drill, and answer design-review questions about safety and operability.
A focused fragment or decision pattern. Try it, then change one condition.
one-off file rename → shell
stateful infrastructure declaration → Terraform
Kubernetes desired-state loop → controllerThe senior skill is choosing the smallest reliable mechanism and explaining its limits.
Open each question only after you have answered it aloud.
A fresh clone can build, test, and run it with documented commands.
It converges across create/update/restart/delete with narrow permissions and status.
When a simpler shell, Python, Terraform, or existing controller solves the task reliably.
Complete this before starting the next chapter.
From a clean clone, build and run platformctl against fixtures and kind.
Create, update, and delete PlatformEnvironment; show tests and CI evidence.
Explain identity boundaries, failure handling, and why Go was appropriate.
Use the official source when a version-sensitive detail changes.
Commands used repeatedly in the labs.
go version
go mod init example.com/platformctl
go fmt ./...
go vet ./...
go test ./...
go test -race ./...
go test -fuzz=FuzzParseReport ./internal/reportkind create cluster --name go-platform
kubectl config current-context
kubectl create token platform-reader -n lab
kubectl get platformenvironments
kubectl get namespace,resourcequota -AStart with evidence; do not guess from the last error line.
Nil dereference · slice aliasing · ignored error · leaked goroutine · data race
Wrong account/region · first page only · throttling loops · unbounded body · missing deadline
Stale resourceVersion · broad RBAC · invalid owner scope · status loop · assuming envtest runs GC
Use these terms precisely in code reviews.
Module: versioned collection of packages. Interface: behavior contract. Context: cancellation/deadline signal. Goroutine: concurrent execution unit.
CRD: custom resource definition. Reconciliation: convergence toward desired state. Finalizer: deletion hold for cleanup. Condition: structured status signal.
Idempotency: repeated operation has the same desired effect. Backpressure: limit incoming work. Observed generation: spec revision reflected in status.