Appendix A: Cheat Sheet
Tested with Go 1.26.9 and golangci-lint 2.14.0 on macOS (Apple Silicon). The code snippets are excerpts from compiled and tested files; the square brackets name the day on which the topic is covered in detail.
Syntax and idioms
Types, constants, methods and functions at package level [Day 1, 2]:
type Level int
const (
Debug Level = iota // 0, 1, 2 …
Info
Warn
)
type Entry struct {
Path string `json:"path"` // struct tag for encoding/json
Status int `json:"status,omitempty"`
}
type Summary struct{ n int }
func (s *Summary) Add(e Entry) { s.n++ } // pointer receiver: may modify
func (s Summary) Count() int { return s.n }
type Server struct {
*slog.Logger // embedding: s.Info(...) calls s.Logger.Info(...)
addr string
}
func div(a, b int) (int, error) { // multiple return values, error last
if b == 0 {
return 0, fmt.Errorf("division durch 0")
}
return a / b, nil
}Inside a function:
var n int // zero value: 0, "", false, nil
s := "Grüße" // type is inferred
x, y := 1, 2
x, y = y, x // swap without a helper variable
p := new(int) // *int set to 0; since Go 1.26 also new(42)
e := Entry{Path: "/", Status: 200}
ep := &Entry{Path: "/api"} // pointer to a struct literal
ep.Status = 201 // dereferenced automatically
if v, ok := m["k"]; ok { // init statement, scope only inside the if
fmt.Println(v)
}
switch {
case n < 0:
fmt.Println("negativ")
case n == 0, n == 1:
fmt.Println("klein") // no break needed, fallthrough is explicit
default:
fmt.Println("groß")
}
for i := range 3 { // 0, 1, 2 (Go 1.22)
fmt.Println(i)
}
for i, r := range s { // byte index and rune
fmt.Println(i, string(r))
}
for n < 10 { // "while"
n++
}
defer f.Close() // runs on return, LIFO
add := func(a int) int { return a + n } // closure sees n| Verb | Output | Example |
|---|---|---|
%v / %+v |
value / with field names | {/api 201} / {Path:/api Status:201} |
%#v |
Go syntax | main.Entry{Path:"/api", Status:201} |
%q / %T |
quoted / type | "a\tb" / main.Entry |
%w |
only in fmt.Errorf: wrap an error |
fmt.Errorf("x: %w", err) |
You write time formats with the reference date
2006-01-02 15:04:05 -0700 or the constants
time.DateOnly, time.DateTime,
time.RFC3339 [Day 2, 7].
Slices, maps, strings
Slices [Day 1]:
s := []string{"helm", "kubectl"}
s = append(s, "bao") // may reallocate: always assign
buf := make([]byte, 0, 4096) // length 0, capacity 4096
t := s[1:3] // view of the same array, no copy
c := slices.Clone(s) // a real copy
slices.Sort(s) // ascending
slices.SortFunc(s, func(a, b string) int { return cmp.Compare(len(a), len(b)) })
i := slices.Index(s, "bao") // -1 if not present
ok := slices.Contains(s, "helm")
s = slices.DeleteFunc(s, func(x string) bool { return x == "helm" })Maps [Day 1, 2]:
m := map[string]int{"http": 80} // literal
m["https"] = 443
v, found := m["ssh"] // comma-ok: 0, false
delete(m, "http")
for _, k := range slices.Sorted(maps.Keys(m)) { // print sorted
fmt.Println(k, m[k])
}
var nilMap map[string]int // reading ok, writing: panic
clear(m) // delete all entries
set := map[string]struct{}{"a": {}} // set without storage for valuesStrings and numbers [Day 1, 4]:
before, after, cut := strings.Cut("k=v=w", "=") // "k", "v=w", true
rest, hadV := strings.CutPrefix("v1.2.3", "v")
fields := strings.Fields(" a b ") // ["a" "b"]
for part := range strings.SplitSeq("a,b,c", ",") { // iterator, Go 1.24
fmt.Println(part)
}
var sb strings.Builder // build strings efficiently
fmt.Fprintf(&sb, "%s=%d\n", "port", 8080)
n, err := strconv.Atoi("42")
q := strconv.Quote("a\tb") // "\"a\\tb\""
runes := utf8.RuneCountInString("Grüße") // 5 characters, len() = 7 bytesErrors
Sentinel and custom type [Day 3]:
var ErrNotFound = errors.New("nicht gefunden") // sentinel
type CheckError struct { // custom type with data
Name string
Err error
}
func (e *CheckError) Error() string { return e.Name + ": " + e.Err.Error() }
func (e *CheckError) Unwrap() error { return e.Err } // for Is/AsWrapping and checking:
data, err := os.ReadFile(path)
if err != nil {
return fmt.Errorf("config %s: %w", path, err) // context + cause
}
if errors.Is(err, fs.ErrNotExist) { // sentinel anywhere in the chain?
fmt.Println("fehlt")
}
var ce *CheckError
if errors.As(err, &ce) { // type in the chain? Then ce is filled
fmt.Println(ce.Name)
}
if ce, ok := errors.AsType[*CheckError](err); ok { // Go 1.26
fmt.Println(ce.Name)
}
both := fmt.Errorf("%w (%w)", ErrNotFound, err) // two causes
all := errors.Join(errors.New("a"), nil, errors.New("b")) // nil is ignoredRecover panics only at boundaries (named return value
err):
defer func() { // turn a panic into an error – only at boundaries (handlers, workers)
if r := recover(); r != nil {
err = fmt.Errorf("panic: %v", r)
}
}()Rules: never ignore errors and never handle them twice (log
or return), never compare error texts with
strings.Contains, no secrets in error messages.
Interfaces and generics
Interfaces are satisfied implicitly [Day 2]:
type Parser interface { // keep it small: one method
Parse(line string) (Entry, error)
}
type JSONParser struct{}
func (JSONParser) Parse(line string) (Entry, error) { return Entry{}, nil }
var _ Parser = JSONParser{} // compiler checks: satisfies the interface
func describe(v any) string {
switch x := v.(type) { // type switch
case nil:
return "nil"
case string:
return "string " + x
case fmt.Stringer:
return x.String()
case io.Reader:
return "Reader"
default:
return fmt.Sprintf("%T", x)
}
}Generics [Day 13]:
func Map[T, U any](in []T, f func(T) U) []U {
out := make([]U, 0, len(in))
for _, v := range in {
out = append(out, f(v))
}
return out
}
func MaxOf[T cmp.Ordered](a, b T) T { return max(a, b) } // max is built in
type Number interface{ ~int | ~int64 | ~float64 } // type set, ~ = custom types too
func Sum[T Number](xs ...T) (s T) {
for _, x := range xs {
s += x
}
return s
}
type Set[T comparable] map[T]struct{}
func (s Set[T]) Add(v T) { s[v] = struct{}{} }
func (s Set[T]) Has(v T) bool { _, ok := s[v]; return ok }
func (s Set[T]) All() iter.Seq[T] { return maps.Keys(s) }Iterators (range-over-func) [Day 4, 13]:
func Lines(text string) iter.Seq2[int, string] { // custom iterator
return func(yield func(int, string) bool) {
for i, l := range strings.Split(text, "\n") {
if !yield(i+1, l) { // false: the caller did a break
return
}
}
}
}
func useIter() {
for n, l := range Lines("a\nb") { // range-over-func, Go 1.23
fmt.Println(n, l)
}
names := slices.Collect(maps.Keys(map[string]int{"a": 1})) // Seq -> slice
sorted := slices.Sorted(slices.Values([]int{3, 1, 2}))
fmt.Println(names, sorted)
}Goroutines, channels, select
var wg sync.WaitGroup
for _, u := range urls {
wg.Go(func() { _ = check(u) }) // Go 1.25; each iteration has its own u
}
wg.Wait()
ch := make(chan int, 10) // buffered: sending blocks only at 10
go func() {
defer close(ch) // only the sender closes
for i := range 3 {
ch <- i
}
}()
for v := range ch { // ends after close
fmt.Println(v)
}
select { // waits for the first ready event
case v, ok := <-ch:
fmt.Println(v, ok) // ok == false: channel closed
case <-time.After(2 * time.Second):
fmt.Println("Timeout")
case <-ctx.Done():
return ctx.Err()
}Worker pool with a fixed size [Day 8, 15]:
results := make([]error, len(urls))
jobs := make(chan int)
for range 8 { // 8 workers
wg.Go(func() {
for i := range jobs {
results[i] = check(urls[i]) // own index: no lock
}
})
}
for i := range urls {
jobs <- i
}
close(jobs)
wg.Wait()errgroup with a limit and cancellation
(golang.org/x/sync/errgroup) [Day 8]:
g, gctx := errgroup.WithContext(ctx) // the first error cancels gctx
g.SetLimit(4) // at most 4 at a time
for _, u := range urls {
g.Go(func() error {
req, err := http.NewRequestWithContext(gctx, http.MethodHead, u, nil)
if err != nil {
return err
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return fmt.Errorf("%s: %w", u, err)
}
return resp.Body.Close()
})
}
if err := g.Wait(); err != nil { // waits for all, returns the first error
return err
}Mutex, atomic, Once:
var mu sync.Mutex // protects fields that belong together
counts := map[string]int{}
mu.Lock()
counts["a"]++
mu.Unlock()
var n atomic.Int64 // a single counter: atomic is enough
n.Add(1)
loadConfig := sync.OnceValue(func() string { return "einmal berechnet" })
fmt.Println(loadConfig(), n.Load())| Rule | Why |
|---|---|
Every goroutine needs an end (ctx, close) |
otherwise a goroutine leak |
| Only the sender closes a channel | sending on a closed channel: panic |
A nil channel in select blocks
forever |
that is how you switch cases off |
| Shared state: mutex or channel, never “it’ll be fine” | go test -race finds it |
context
ctx, stop := signal.NotifyContext(context.Background(),
os.Interrupt, syscall.SIGTERM) // Ctrl+C, pod stop
defer stop()
ctx, cancel := context.WithTimeout(ctx, 15*time.Second) // total budget
defer cancel() // always: frees the timer
err := work(ctx) // always pass ctx through as the first parameter
if errors.Is(err, context.DeadlineExceeded) {
return errors.New("zu langsam")
}
ctx2, cancel2 := context.WithCancelCause(ctx)
cancel2(errors.New("config ungültig"))
log.Println(context.Cause(ctx2)) // "config ungültig" instead of just "canceled"
auditCtx := context.WithoutCancel(ctx) // write the audit log even after cancellation
writeAudit(auditCtx)ctx is always the first parameter, never a struct field.
For values (context.WithValue) only request metadata such
as trace IDs, no configuration [Day 7].
net/http: server
ServeMux with methods and wildcards, middleware, timeouts, graceful shutdown [Day 9]:
func newMux(log *slog.Logger) http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNoContent)
})
mux.HandleFunc("GET /api/links/{code}", func(w http.ResponseWriter,
r *http.Request) {
code := r.PathValue("code") // wildcard from the pattern, Go 1.22
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]string{"code": code})
})
return logging(log, mux)
}
func logging(log *slog.Logger, next http.Handler) http.Handler { // middleware
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
next.ServeHTTP(w, r)
log.Info("request", "method", r.Method, "path", r.URL.Path,
"dauer", time.Since(start))
})
}
func serve(ctx context.Context, h http.Handler) error {
srv := &http.Server{Addr: "127.0.0.1:8080", Handler: h,
ReadHeaderTimeout: 5 * time.Second, ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second, IdleTimeout: 60 * time.Second}
errc := make(chan error, 1)
go func() { errc <- srv.ListenAndServe() }()
select {
case err := <-errc:
return err
case <-ctx.Done(): // SIGTERM: no new connections, running ones finish
}
sctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := srv.Shutdown(sctx); err != nil {
return err
}
if err := <-errc; !errors.Is(err, http.ErrServerClosed) {
return err
}
return nil
}net/http: client
func getJSON(ctx context.Context, c *http.Client, url string, v any) error {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return err
}
req.Header.Set("Accept", "application/json")
if tok := os.Getenv("API_TOKEN"); tok != "" { // token only from the environment
req.Header.Set("Authorization", "Bearer "+tok)
}
resp, err := c.Do(req)
if err != nil {
return err
}
defer resp.Body.Close() // always close, otherwise the connection leaks
if resp.StatusCode != http.StatusOK {
msg, _ := io.ReadAll(io.LimitReader(resp.Body, 512))
return fmt.Errorf("%s: %s: %s", url, resp.Status, msg)
}
return json.NewDecoder(resp.Body).Decode(v)
}
var client = &http.Client{Timeout: 5 * time.Second} // never the default without a timeoutRetries only on 429, 5xx and network errors, with backoff and
Retry-After, only for idempotent requests [Day 7].
slog
opts := &slog.HandlerOptions{Level: slog.LevelInfo} // Debug is discarded
var h slog.Handler = slog.NewJSONHandler(os.Stdout, opts)
if dev {
h = slog.NewTextHandler(os.Stderr, opts) // readable in the terminal
}
log := slog.New(h).With("app", "shorturl", "version", "0.1.0")
slog.SetDefault(log) // also for slog.Info(...) and the old log package
log.Info("start", "addr", ":8080")
log.Error("db", "err", os.ErrNotExist, slog.Group("req", "id", 42))
testLog := slog.New(slog.DiscardHandler) // tests: print nothing, Go 1.24Testing
func TestDiv(t *testing.T) {
tests := []struct {
name string
a, b int
want int
wantErr bool
}{
{"normal", 6, 3, 2, false},
{"durch null", 1, 0, 0, true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) { // subtest: go test -run 'TestDiv/null'
got, err := div(tt.a, tt.b)
if (err != nil) != tt.wantErr || got != tt.want {
t.Errorf("div(%d, %d) = %d, %v; will %d", tt.a, tt.b, got, err, tt.want)
}
})
}
}
func writeFile(t *testing.T, content string) string {
t.Helper() // errors point to the caller
p := filepath.Join(t.TempDir(), "x.txt") // deleted automatically
if err := os.WriteFile(p, []byte(content), 0o600); err != nil {
t.Fatal(err) // Fatal aborts the test, Errorf does not
}
return p
}
func TestHTTP(t *testing.T) {
t.Setenv("API_TOKEN", "lab-token") // reset after the test
srv := httptest.NewServer(http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, `{}`) }))
t.Cleanup(srv.Close)
var v map[string]any
if err := getJSON(t.Context(), srv.Client(), srv.URL, &v); err != nil { // 1.24
t.Fatal(err)
}
_ = writeFile(t, "a")
}
func FuzzCut(f *testing.F) {
f.Add("k=v") // seeds: edge cases belong here
f.Fuzz(func(t *testing.T, s string) {
k, v, ok := strings.Cut(s, "=")
if ok && k+"="+v != s {
t.Errorf("Cut(%q) verliert Daten", s)
}
})
}
func BenchmarkDiv(b *testing.B) {
for b.Loop() { // Go 1.24: measures only the body
_, _ = div(10, 3)
}
}
func TestTimeout(t *testing.T) {
synctest.Test(t, func(t *testing.T) { // Go 1.25: virtual clock, no waiting
ctx, cancel := context.WithTimeout(t.Context(), time.Hour)
defer cancel()
<-ctx.Done() // "takes" an hour, runs in microseconds
})
}# Everything, without cache, with race detector; random order, stop at the 1st failure
go test -race -count=1 ./...
go test -shuffle=on -failfast ./...
# Individual tests and subtests (one regex per level, separated by /)
go test -run 'TestDiv/null' -v ./...
# Coverage: overview, per function, in the browser
go test -cover ./...
go test -coverprofile=cover.out ./... && go tool cover -func=cover.out
go tool cover -html=cover.out
# Fuzzing: exactly one fuzz test, one package; findings land in testdata/fuzz/
go test -run '^$' -fuzz '^FuzzCut$' -fuzztime 30s .
# Benchmarks with allocations; run several times for comparison
go test -run '^$' -bench . -benchmem -count=10 ./... > neu.txt
go run golang.org/x/perf/cmd/benchstat@latest alt.txt neu.txt
# Rewrite golden files (custom flag in the test, Day 4) – then read git diff
go test ./cmd/semver -run Golden -update
# Machine-readable for CI, clear the test cache
go test -json ./... > test.json
go clean -testcacheThe go command
go version && go env GOOS GOARCH GOPATH GOMODCACHE
go run ./cmd/tool -flag wert # build and run
go build -o bin/ ./cmd/... # all commands into bin/
go install ./cmd/tool # into $(go env GOPATH)/bin
gofmt -l . && go vet ./... # formatting and analysis
go fix -diff ./... # show modernizers (Go 1.26)
go doc errors.AsType # docs in the terminal, also for your own packages
go doc -all ./internal/logs
go list -f '{{.ImportPath}}: {{.Imports}}' ./...
go version -m bin/tool # build info from a binary
go tool # bundled tools (cover, pprof, ...)
go generate ./... # run //go:generate comments
go clean -cache # clear the build cache
~/go-lab/bin/lint run ./... # golangci-lint, Day 0Modules
go mod init example.com/tool
go get go.yaml.in/yaml/[email protected] # always pin the version
go get -u ./... && go mod tidy # update dependencies
go mod tidy -diff # check only – ideal as a CI gate
go list -m all # all modules in the build
go list -m -u all # which ones have updates?
go mod why go.yaml.in/yaml/v3 # who pulls it in?
go mod graph | grep yaml
go mod verify # check the cache against go.sum
go mod edit -replace example.com/lib=../lib # local copy instead of a version
go mod edit -dropreplace example.com/lib
go mod vendor # dependencies into the repo (air gap)
go work init ./svc ./lib # workspace for multiple modules
go get -tool golang.org/x/vuln/cmd/[email protected] # tool in go.mod (1.24)
go tool govulncheck ./... # known CVEs in the code you use
go mod edit -toolchain=go1.26.9 # pin the toolchain for the teamEnvironment for companies: GOPROXY (internal proxy),
GOPRIVATE=git.firma.de/* (private, without the checksum
DB), GOFLAGS=-mod=vendor. go env -w writes
permanently into the user’s Go configuration – when in doubt, export per
shell instead.
Profiling with pprof
# From benchmarks: CPU and memory profile, then a top list or the web UI
go test -run '^$' -bench . -cpuprofile cpu.out -memprofile mem.out .
go tool pprof -top -nodecount=15 cpu.out
go tool pprof -http=127.0.0.1:0 cpu.out # flame graph in the browser
go tool pprof -sample_index=alloc_space -top mem.out
# In a running service (import _ "net/http/pprof", listen on localhost only!)
curl -s -o cpu.pprof 'http://127.0.0.1:6060/debug/pprof/profile?seconds=10'
curl -s -o heap.pprof http://127.0.0.1:6060/debug/pprof/heap
curl -s 'http://127.0.0.1:6060/debug/pprof/goroutine?debug=1' | head
# Execution trace: scheduler, GC, blocked goroutines
go test -run TestX -trace trace.out . && go tool trace trace.outInteractively in pprof: top,
list functionname, web. Rule of thumb [Day
13]: measure first, then reduce allocations, then the algorithm – never
the other way round.
Cross-compiling and releases
go tool dist list | grep -E '^(linux|darwin|windows)/' # all targets
GOOS=linux GOARCH=arm64 CGO_ENABLED=0 go build -trimpath \
-ldflags "-s -w -X main.version=$(git describe --tags --always)" \
-o dist/tool-linux-arm64 ./cmd/tool
GOOS=windows GOARCH=amd64 go build -o dist/tool.exe ./cmd/tool
file dist/tool-linux-arm64
go version -m dist/tool-linux-arm64 | grep -E 'GOOS|GOARCH'Release tools from Day 14, each via a wrapper with a pinned version:
~/go-lab/bin/goreleaser check # check .goreleaser.yaml
~/go-lab/bin/goreleaser release --snapshot --clean # all archives locally, without upload
docker build --check . # only check the Dockerfile
~/go-lab/bin/actionlint # check GitHub Actions workflows| Variable/flag | Effect |
|---|---|
CGO_ENABLED=0 |
static binary, runs in distroless/scratch |
-trimpath |
no local paths in the binary (reproducible) |
-ldflags "-s -w" |
without symbol and debug tables, smaller |
-X main.version=… |
set a string variable at link time [Day 0] |
GOAMD64=v3 / GOARM64=v8.2 |
newer CPU instructions, only if all target machines have them |