Skip to content
Hands-on IT IT Drills

Day 15: Competition – tool challenges against the clock

Goal: Build seven mini tools against the clock – each from a specification and given tests, until the tests with -race, go vet and the linter are green · Duration: approx. 240 min (feel free to spread over two evenings) · Prerequisite: Day 14

Briefing

  • For each challenge: read the specification, type in the test file, start the stopwatch, write code until ziel (“finish”) reports green.
  • The tests are the referee. Don’t change them – except for your own typos.
  • First the package under internal/ against the tests, then cmd/<tool>/main.go following the familiar pattern: thin main, run(...) returns exit code 0, 1 or 2 (Days 6–8).
  • Allowed: go doc, Appendix A, your Days 1–14. Standard library only.
  • Read the sample solution only once you are green or double the time has passed.
 spec ─► type in *_test.go ─► go test: red ─► code ─► ziel: green ─► time
                                 ▲                 │
                                 └──────── fix it ─┘

Starting lineup

Two shell functions take the routine off your hands: start creates the module, folders and linter configuration and starts the stopwatch; ziel checks everything and reports the time only when everything is green.

cat > ~/go-lab/wettkampf.sh <<'EOF'
# Helpers for Day 15 – load with: source ~/go-lab/wettkampf.sh
start() { # start TOOL PAKET: Modul anlegen und Stoppuhr starten
  mkdir -p ~/go-lab/tag15-"$1"/{cmd/"$1",internal/"$2"} &&
    cd ~/go-lab/tag15-"$1" || return
  [ -f go.mod ] || go mod init example.com/"$1"
  printf 'version: "2"\nlinters:\n  exclusions:\n    presets: [%s]\n' \
    std-error-handling > .golangci.yml
  date +%s > .start
}
ziel() { # ziel: alle Prüfungen; nur wenn alles grün ist, zählt die Zeit
  test -z "$(gofmt -l .)" || { gofmt -l .; return 1; }
  go vet ./... && go test -race -count=1 ./... && ~/go-lab/bin/lint run ./... ||
    return 1
  echo "Zeit: $(( ($(date +%s) - $(cat .start)) / 60 )) min"
}
EOF
source ~/go-lab/wettkampf.sh
command -v start ziel

Expected:

start
ziel

Tip: Functions only live in the current shell. In every new terminal, run source ~/go-lab/wettkampf.sh first.

Challenge 1: portwait – waiting with backoff

Time limit: 20 min · Points: 10 · Building blocks: context, timers, function types (Days 3, 7)

Specification

  • wait.Backoff(initial, limit, n) returns the pause after failed attempt n (from 0): initial·2^n, at most limit – without overflow, even with n = 100.
  • wait.Port(ctx, addr, wait.Options) tries to open a TCP connection via Options.Dial (default: net.Dialer.DialContext) until it succeeds, and returns the number of attempts. Defaults: Initial 100 ms, Max 2 s.
  • After every failed attempt, Port calls Options.OnRetry(versuch, err, pause) – if set.
  • If ctx ends, Port returns immediately; the error contains context.DeadlineExceeded or context.Canceled (checkable with errors.Is).
  • CLI: portwait [-timeout 30s] [-max 2s] [-v] host:port... with a shared time budget. Exit 0 = all open, 1 = timeout, 2 = wrong invocation.

Tests

start portwait wait
cat > internal/wait/wait_test.go <<'EOF'
package wait

import (
    "context"
    "errors"
    "net"
    "slices"
    "syscall"
    "testing"
    "time"
)

func TestBackoff(t *testing.T) {
    ms := time.Millisecond
    tests := []struct {
        n    int
        want time.Duration
    }{
        {0, 100 * ms}, {1, 200 * ms}, {3, 800 * ms}, {4, 1600 * ms},
        {5, 2 * time.Second}, {100, 2 * time.Second}, // 100: kein Überlauf!
    }
    for _, tt := range tests {
        if got := Backoff(100*ms, 2*time.Second, tt.n); got != tt.want {
            t.Errorf("Backoff(n=%d) = %v, will %v", tt.n, got, tt.want)
        }
    }
}

func TestPortOffen(t *testing.T) {
    ln, err := net.Listen("tcp", "127.0.0.1:0")
    if err != nil {
        t.Fatal(err)
    }
    defer ln.Close()
    n, err := Port(context.Background(), ln.Addr().String(), Options{})
    if err != nil || n != 1 {
        t.Errorf("Port = %d, %v; will 1, nil", n, err)
    }
}

func TestPortRetryMitBackoff(t *testing.T) {
    calls := 0
    dial := func(ctx context.Context, _, _ string) (net.Conn, error) {
        calls++
        if calls <= 3 {
            return nil, syscall.ECONNREFUSED
        }
        c1, c2 := net.Pipe()
        c2.Close()
        return c1, nil
    }
    var waits []time.Duration
    o := Options{Initial: time.Millisecond, Max: 3 * time.Millisecond, Dial: dial,
        OnRetry: func(_ int, err error, d time.Duration) {
            if !errors.Is(err, syscall.ECONNREFUSED) {
                t.Errorf("OnRetry err = %v", err)
            }
            waits = append(waits, d)
        }}
    n, err := Port(context.Background(), "lab:1", o)
    if err != nil || n != 4 {
        t.Fatalf("Port = %d, %v; will 4, nil", n, err)
    }
    ms := time.Millisecond
    want := []time.Duration{ms, 2 * ms, 3 * ms} // verdoppelt, dann gedeckelt
    if !slices.Equal(waits, want) {
        t.Errorf("Wartezeiten = %v, will %v", waits, want)
    }
}

func TestPortDeadline(t *testing.T) {
    ln, err := net.Listen("tcp", "127.0.0.1:0")
    if err != nil {
        t.Fatal(err)
    }
    addr := ln.Addr().String()
    ln.Close() // Port ist jetzt zu
    ctx, cancel := context.WithTimeout(context.Background(), 150*time.Millisecond)
    defer cancel()
    start := time.Now()
    _, err = Port(ctx, addr, Options{Initial: 10 * time.Millisecond})
    if !errors.Is(err, context.DeadlineExceeded) {
        t.Errorf("err = %v, will DeadlineExceeded", err)
    }
    if d := time.Since(start); d > time.Second {
        t.Errorf("Abbruch nach %v – context ignoriert?", d)
    }
}
EOF
go test ./internal/wait

Expected (abbreviated):

# example.com/portwait/internal/wait [example.com/portwait/internal/wait.test]
internal/wait/wait_test.go:23:13: undefined: Backoff
internal/wait/wait_test.go:35:12: undefined: Port
internal/wait/wait_test.go:35:59: undefined: Options
…
FAIL    example.com/portwait/internal/wait [build failed]

Red is the starting signal. The stopwatch is running – from here on you’re on your own.

Sample solution

cat > internal/wait/wait.go <<'EOF'
// Package wait waits for TCP ports – with context and exponential backoff.
package wait

import (
    "context"
    "fmt"
    "net"
    "time"
)

// Backoff returns the pause after failed attempt n (from 0): initial·2^n,
// at most limit. The loop only doubles up to limit – no overflow.
func Backoff(initial, limit time.Duration, n int) time.Duration {
    d := initial
    for range n {
        if d >= limit/2 {
            return limit
        }
        d *= 2
    }
    return min(d, limit)
}

// Options controls Port. Zero values get defaults.
type Options struct {
    Initial time.Duration // erste Pause, Default 100ms
    Max     time.Duration // längste Pause, Default 2s
    Dial    func(ctx context.Context, network, addr string) (net.Conn, error)
    OnRetry func(attempt int, err error, wait time.Duration) // optional
}

// Port tries to reach addr until it succeeds or ctx ends,
// and returns the number of attempts.
func Port(ctx context.Context, addr string, o Options) (int, error) {
    if o.Initial <= 0 {
        o.Initial = 100 * time.Millisecond
    }
    if o.Max <= 0 {
        o.Max = 2 * time.Second
    }
    if o.Dial == nil {
        var d net.Dialer
        o.Dial = d.DialContext
    }
    for attempt := 1; ; attempt++ {
        dctx, cancel := context.WithTimeout(ctx, time.Second) // pro Versuch
        conn, err := o.Dial(dctx, "tcp", addr)
        cancel()
        if err == nil {
            return attempt, conn.Close()
        }
        wait := Backoff(o.Initial, o.Max, attempt-1)
        if o.OnRetry != nil {
            o.OnRetry(attempt, err, wait)
        }
        select {
        case <-ctx.Done():
            return attempt, fmt.Errorf("%s: %w (letzter Fehler: %v)",
                addr, ctx.Err(), err)
        case <-time.After(wait):
        }
    }
}
EOF
cat > cmd/portwait/main.go <<'EOF'
// portwait waits until TCP ports are open: portwait [-timeout 30s] host:port...
// Day 15 of "Go hands-on".
package main

import (
    "context"
    "flag"
    "fmt"
    "io"
    "os"
    "os/signal"
    "time"

    "example.com/portwait/internal/wait"
)

func main() {
    ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
    defer stop()
    os.Exit(run(ctx, os.Args[1:], os.Stdout, os.Stderr))
}

func run(ctx context.Context, args []string, stdout, stderr io.Writer) int {
    fl := flag.NewFlagSet("portwait", flag.ContinueOnError)
    fl.SetOutput(stderr)
    timeout := fl.Duration("timeout", 30*time.Second, "Gesamtbudget für alle Ports")
    maxWait := fl.Duration("max", 2*time.Second, "längste Pause zwischen Versuchen")
    verbose := fl.Bool("v", false, "jeden Fehlversuch melden")
    if err := fl.Parse(args); err != nil {
        return 2
    }
    if fl.NArg() == 0 {
        fmt.Fprintln(stderr, "Aufruf: portwait [-timeout 30s] [-v] host:port...")
        return 2
    }
    ctx, cancel := context.WithTimeout(ctx, *timeout)
    defer cancel()

    o := wait.Options{Max: *maxWait}
    if *verbose {
        o.OnRetry = func(n int, err error, d time.Duration) {
            fmt.Fprintf(stderr, "  Versuch %d: %v (warte %v)\n", n, err, d)
        }
    }
    start := time.Now()
    for _, addr := range fl.Args() {
        n, err := wait.Port(ctx, addr, o)
        if err != nil {
            fmt.Fprintln(stderr, "portwait:", err)
            return 1
        }
        fmt.Fprintf(stdout, "✔ %s offen (%d Versuche, %v)\n", addr, n,
            time.Since(start).Round(time.Millisecond))
    }
    return 0
}
EOF
ziel

Expected (your time will differ):

?       example.com/portwait/cmd/portwait   [no test files]
ok      example.com/portwait/internal/wait  1.327s
0 issues.
Zeit: 17 min

Why? Backoff checks whether limit is reached before doubling – initial << n would have overflowed long before n = 100 (Day 4). The select on ctx.Done() and time.After aborts even in the middle of a pause. The test replaces Dial with a function that returns ECONNREFUSED three times: no network, no waiting, deterministic.

go build -o bin/portwait ./cmd/portwait
(sleep 2; python3 -m http.server 8099 --bind 127.0.0.1 >/dev/null 2>&1) &
./bin/portwait -v 127.0.0.1:8099; echo "exit=$?"
pkill -f 'http.server 8099'
./bin/portwait -timeout 1s 127.0.0.1:8099; echo "exit=$?"

Expected (abbreviated, times vary):

  Versuch 1: dial tcp 127.0.0.1:8099: connect: connection refused (warte 100ms)
  Versuch 2: dial tcp 127.0.0.1:8099: connect: connection refused (warte 200ms)
  …
  Versuch 5: dial tcp 127.0.0.1:8099: connect: connection refused (warte 1.6s)
✔ 127.0.0.1:8099 offen (6 Versuche, 3.105s)
exit=0
portwait: 127.0.0.1:8099: context deadline exceeded (letzter Fehler: dial tcp …
exit=1

This is waitport from the Day 3 challenge, all grown up: a total budget via context as in ghrel (Day 7), backoff instead of a fixed pause, and -v shows every attempt.

Save your progress? Sign up for free

Challenge 2: dupfind – duplicates via SHA-256

Time limit: 30 min · Points: 15 · Building blocks: WalkDir, worker pool, maps (Days 6, 8)

Specification

  • dup.Find(ctx, root, workers) searches root recursively and returns []dup.Group{Size, Hash, Paths} for files with identical content.
  • Only regular files with more than 0 bytes; symlinks and empty files don’t count. Only files whose size occurs more than once get hashed.
  • SHA-256 as a hex string, Paths sorted. Groups sorted by Wasted() (size × number of copies) descending, then by first path.
  • Hashing with workers goroutines; the same result with 1 and 8 workers. A canceled ctx returns context.Canceled, a missing folder an error with os.ErrNotExist.
  • CLI: dupfind [-w N] [-json] ORDNER, the default for -w is the number of CPU cores. Exit 0 = ran (even with findings), 1 = error, 2 = invocation.

Tests

start dupfind dup
cat > internal/dup/dup_test.go <<'EOF'
package dup

import (
    "context"
    "errors"
    "os"
    "path/filepath"
    "reflect"
    "testing"
)

// tree creates files relative to a TempDir and returns its path.
func tree(t *testing.T, files map[string]string) string {
    t.Helper()
    root := t.TempDir()
    for name, content := range files {
        p := filepath.Join(root, name)
        if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
            t.Fatal(err)
        }
        if err := os.WriteFile(p, []byte(content), 0o644); err != nil {
            t.Fatal(err)
        }
    }
    return root
}

func TestFind(t *testing.T) {
    root := tree(t, map[string]string{
        "a.txt":     "hallo",
        "sub/b.txt": "hallo",  // Duplikat von a.txt
        "c.txt":     "hallx",  // gleiche Größe, anderer Inhalt
        "d.txt":     "hallo!", // andere Größe
        "leer1":     "",       // leere Dateien zählen nicht
        "leer2":     "",
    })
    if err := os.Symlink("a.txt", filepath.Join(root, "link")); err != nil {
        t.Fatal(err)
    }
    for _, workers := range []int{1, 8} {
        got, err := Find(context.Background(), root, workers)
        if err != nil {
            t.Fatal(err)
        }
        want := []Group{{
            Size: 5,
            Hash: "d3751d33f9cd5049c4af2b462735457e4d3baf130bcbb87f389e349fbaeb20b9",
            Paths: []string{filepath.Join(root, "a.txt"),
                filepath.Join(root, "sub", "b.txt")},
        }}
        if !reflect.DeepEqual(got, want) {
            t.Errorf("workers=%d:\n got %+v\nwant %+v", workers, got, want)
        }
    }
}

func TestFindSortierung(t *testing.T) {
    root := tree(t, map[string]string{
        "k1": "kurz", "k2": "kurz",
        "l1": "deutlich länger", "l2": "deutlich länger", "l3": "deutlich länger",
    })
    got, err := Find(context.Background(), root, 4)
    if err != nil {
        t.Fatal(err)
    }
    if len(got) != 2 || len(got[0].Paths) != 3 || got[0].Wasted() != 2*16 {
        t.Errorf("größte Verschwendung zuerst erwartet: %+v", got)
    }
}

func TestFindAbbruch(t *testing.T) {
    root := tree(t, map[string]string{"a": "x", "b": "x"})
    ctx, cancel := context.WithCancel(context.Background())
    cancel()
    if _, err := Find(ctx, root, 2); !errors.Is(err, context.Canceled) {
        t.Errorf("err = %v, will context.Canceled", err)
    }
}

func TestFindFehlenderOrdner(t *testing.T) {
    _, err := Find(context.Background(), "/gibt/es/nicht", 2)
    if !errors.Is(err, os.ErrNotExist) {
        t.Errorf("err = %v, will os.ErrNotExist", err)
    }
}
EOF

Sample solution

cat > internal/dup/dup.go <<'EOF'
// Package dup finds duplicate files via SHA-256 – with a worker pool.
package dup

import (
    "cmp"
    "context"
    "crypto/sha256"
    "encoding/hex"
    "errors"
    "io"
    "io/fs"
    "os"
    "path/filepath"
    "slices"
    "sync"
)

// Group is a set of files with identical content.
type Group struct {
    Size  int64
    Hash  string   // SHA-256, hex
    Paths []string // sortiert
}

// Wasted is the extra space the copies occupy.
func (g Group) Wasted() int64 { return g.Size * int64(len(g.Paths)-1) }

// Find searches root. Only files whose size occurs more than once get hashed.
func Find(ctx context.Context, root string, workers int) ([]Group, error) {
    bySize := map[int64][]string{}
    err := filepath.WalkDir(root, func(p string, d fs.DirEntry, err error) error {
        if err != nil {
            return err
        }
        if err := ctx.Err(); err != nil {
            return err
        }
        if !d.Type().IsRegular() { // Ordner, Symlinks, Sockets
            return nil
        }
        info, err := d.Info()
        if err != nil {
            return err
        }
        if info.Size() > 0 {
            bySize[info.Size()] = append(bySize[info.Size()], p)
        }
        return nil
    })
    if err != nil {
        return nil, err
    }

    var paths []string
    for _, ps := range bySize {
        if len(ps) > 1 {
            paths = append(paths, ps...)
        }
    }
    sums, err := hashAll(ctx, paths, workers)
    if err != nil {
        return nil, err
    }

    byHash := map[string]*Group{}
    for i, p := range paths {
        g := byHash[sums[i]]
        if g == nil {
            g = &Group{Hash: sums[i]}
            byHash[sums[i]] = g
        }
        g.Paths = append(g.Paths, p)
    }
    var groups []Group
    for _, g := range byHash {
        if len(g.Paths) < 2 {
            continue
        }
        slices.Sort(g.Paths)
        info, err := os.Stat(g.Paths[0])
        if err != nil {
            return nil, err
        }
        g.Size = info.Size()
        groups = append(groups, *g)
    }
    slices.SortFunc(groups, func(a, b Group) int {
        return cmp.Or(cmp.Compare(b.Wasted(), a.Wasted()),
            cmp.Compare(a.Paths[0], b.Paths[0]))
    })
    return groups, nil
}

// hashAll hashes paths with workers goroutines; each one writes only its own index.
func hashAll(ctx context.Context, paths []string, workers int) ([]string, error) {
    sums := make([]string, len(paths))
    errs := make([]error, len(paths))
    jobs := make(chan int)
    var wg sync.WaitGroup
    for range max(workers, 1) {
        wg.Go(func() {
            for i := range jobs {
                sums[i], errs[i] = hashFile(paths[i])
            }
        })
    }
feed:
    for i := range paths {
        select {
        case jobs <- i:
        case <-ctx.Done():
            break feed
        }
    }
    close(jobs)
    wg.Wait()
    if err := ctx.Err(); err != nil {
        return nil, err
    }
    return sums, errors.Join(errs...)
}

func hashFile(path string) (string, error) {
    f, err := os.Open(path)
    if err != nil {
        return "", err
    }
    defer f.Close()
    h := sha256.New()
    if _, err := io.Copy(h, f); err != nil {
        return "", err
    }
    return hex.EncodeToString(h.Sum(nil)), nil
}
EOF
cat > cmd/dupfind/main.go <<'EOF'
// dupfind finds duplicate files: dupfind [-w 8] [-json] ORDNER
// Day 15 of "Go hands-on".
package main

import (
    "context"
    "encoding/json"
    "flag"
    "fmt"
    "io"
    "os"
    "os/signal"
    "runtime"

    "example.com/dupfind/internal/dup"
)

func main() {
    ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
    defer stop()
    os.Exit(run(ctx, os.Args[1:], os.Stdout, os.Stderr))
}

func run(ctx context.Context, args []string, stdout, stderr io.Writer) int {
    fl := flag.NewFlagSet("dupfind", flag.ContinueOnError)
    fl.SetOutput(stderr)
    workers := fl.Int("w", runtime.NumCPU(), "parallele Hasher")
    asJSON := fl.Bool("json", false, "JSON-Ausgabe")
    if err := fl.Parse(args); err != nil {
        return 2
    }
    if fl.NArg() != 1 {
        fmt.Fprintln(stderr, "Aufruf: dupfind [-w N] [-json] ORDNER")
        return 2
    }
    groups, err := dup.Find(ctx, fl.Arg(0), *workers)
    if err != nil {
        fmt.Fprintln(stderr, "dupfind:", err)
        return 1
    }
    if *asJSON {
        _ = json.NewEncoder(stdout).Encode(groups)
        return 0
    }
    var wasted int64
    for _, g := range groups {
        fmt.Fprintf(stdout, "%d × %d B  %s\n", len(g.Paths), g.Size, g.Hash[:12])
        for _, p := range g.Paths {
            fmt.Fprintln(stdout, "  "+p)
        }
        wasted += g.Wasted()
    }
    fmt.Fprintf(stdout, "%d Gruppen, %d B verschwendet\n", len(groups), wasted)
    return 0
}
EOF
ziel

Why? The size filter saves almost all of the hashing work: two files of different sizes can never be identical. In the pool, each worker writes only sums[i] and errs[i] – no lock needed (Day 8). The label feed: is needed because a break inside the select would otherwise only leave the select.

go build -o bin/dupfind ./cmd/dupfind
mkdir -p demo/sub && printf 'hallo\n' > demo/a.txt
cp demo/a.txt demo/sub/a-kopie.txt && printf 'anders\n' > demo/b.txt
cp /usr/share/dict/words demo/w1 && cp demo/w1 demo/sub/w2
./bin/dupfind demo; echo "exit=$?"
./bin/dupfind "$(go env GOROOT)/src" | tail -1
./bin/dupfind /nix; echo "exit=$?"

Expected (numbers for GOROOT depend on the Go version):

2 × 2493885 B  be41ad97963b
  demo/sub/w2
  demo/w1
2 × 6 B  622cb3371c1a
  demo/a.txt
  demo/sub/a-kopie.txt
2 Gruppen, 2493891 B verschwendet
exit=0
154 Gruppen, 3149665 B verschwendet
dupfind: lstat /nix: no such file or directory
exit=1

The word list /usr/share/dict/words exists on every Mac – a quick way to get a large file. The Go source itself contains 154 groups of identical files, mostly test data.

Save your progress? Sign up for free

Challenge 3: jsonq – a mini jq

Time limit: 30 min · Points: 15 · Building blocks: parser, type switch, any, sentinels, fuzzing (Days 3, 4, 6)

Specification

  • query.Eval(v, expr) evaluates a path on a value from encoding/json (map[string]any, []any, …) and returns []any.
  • Syntax: . (everything), .key, .a.b, [N], [-1] (from the end), [] (all elements; for objects the values sorted by key) – combined freely, as in .items[].name.
  • Like jq: .x on null or a missing key returns null, as does an index outside the array.
  • Errors: an expression without a leading dot, an empty key, a broken index → ErrSyntax; .x on a number/string, [N]/[] on a non-array → ErrType. No input may trigger a panic.
  • CLI: jsonq [-r] AUSDRUCK [DATEI], reads stdin when there is no file, processes multiple JSON values in a row (JSON Lines), prints each result compactly, with -r strings without quotes. Numbers stay exact (98000000, not 9.8e+07). Exit 0 = ok, 1 = input or type error, 2 = invocation or syntax error.

Tests

start jsonq query
cat > internal/query/query_test.go <<'EOF'
package query

import (
    "encoding/json"
    "errors"
    "reflect"
    "testing"
)

const doc = `{"name":"shop","items":[{"name":"a","tags":["x"]},
    {"name":"b","price":2}],"meta":null}`

func TestEval(t *testing.T) {
    var v any
    if err := json.Unmarshal([]byte(doc), &v); err != nil {
        t.Fatal(err)
    }
    tests := []struct {
        expr string
        want []any
    }{
        {".", []any{v}},
        {".name", []any{"shop"}},
        {".items[0].name", []any{"a"}},
        {".items[].name", []any{"a", "b"}},
        {".items[-1].price", []any{2.0}},
        {".items[5]", []any{nil}},
        {".fehlt.x", []any{nil}},
        {".meta.x", []any{nil}},
        {".items[].tags[0]", []any{"x", nil}},
        {".items[1][]", []any{"b", 2.0}}, // Objekt: Werte nach Schlüssel sortiert
    }
    for _, tt := range tests {
        t.Run(tt.expr, func(t *testing.T) {
            got, err := Eval(v, tt.expr)
            if err != nil {
                t.Fatal(err)
            }
            if !reflect.DeepEqual(got, tt.want) {
                t.Errorf("got %#v, will %#v", got, tt.want)
            }
        })
    }
}

func TestEvalFehler(t *testing.T) {
    var v any
    if err := json.Unmarshal([]byte(doc), &v); err != nil {
        t.Fatal(err)
    }
    tests := []struct {
        expr string
        want error
    }{
        {"name", ErrSyntax},
        {".a..b", ErrSyntax},
        {".a[x]", ErrSyntax},
        {".a[1", ErrSyntax},
        {".name[0]", ErrType},
        {".name.x", ErrType},
        {".name[]", ErrType},
    }
    for _, tt := range tests {
        if _, err := Eval(v, tt.expr); !errors.Is(err, tt.want) {
            t.Errorf("Eval(%q) err = %v, will %v", tt.expr, err, tt.want)
        }
    }
}

func FuzzEval(f *testing.F) {
    f.Add(".items[].name")
    f.Add(".a[-1][]")
    var v any
    _ = json.Unmarshal([]byte(doc), &v)
    f.Fuzz(func(t *testing.T, expr string) {
        _, _ = Eval(v, expr) // darf Fehler liefern, aber nie paniken
    })
}
EOF

Sample solution

cat > internal/query/query.go <<'EOF'
// Package query evaluates simple jq paths: . .a .a.b .a[0] .a[-1] .a[]
package query

import (
    "errors"
    "fmt"
    "maps"
    "slices"
    "strconv"
    "strings"
)

// Sentinels: syntax error in the expression or wrong type in the document.
var (
    ErrSyntax = errors.New("syntaxfehler")
    ErrType   = errors.New("typfehler")
)

type kind int

const (
    field kind = iota // .name
    index             // [N]
    iter              // []
)

type step struct {
    kind kind
    key  string
    n    int
}

// parse splits ".items[0].name" into steps.
func parse(expr string) ([]step, error) {
    rest, ok := strings.CutPrefix(expr, ".")
    if !ok {
        return nil, fmt.Errorf("%w: %q muss mit . beginnen", ErrSyntax, expr)
    }
    var steps []step
    for rest != "" {
        switch rest[0] {
        case '[':
            inner, after, ok := strings.Cut(rest[1:], "]")
            if !ok {
                return nil, fmt.Errorf("%w: ] fehlt in %q", ErrSyntax, expr)
            }
            if inner == "" {
                steps = append(steps, step{kind: iter})
            } else {
                n, err := strconv.Atoi(inner)
                if err != nil {
                    return nil, fmt.Errorf("%w: Index %q", ErrSyntax, inner)
                }
                steps = append(steps, step{kind: index, n: n})
            }
            rest = after
        case '.':
            rest = rest[1:]
            if rest == "" || rest[0] == '.' {
                return nil, fmt.Errorf("%w: leerer Schlüssel in %q", ErrSyntax, expr)
            }
        default:
            end := strings.IndexAny(rest, ".[")
            if end < 0 {
                end = len(rest)
            }
            steps = append(steps, step{kind: field, key: rest[:end]})
            rest = rest[end:]
        }
    }
    return steps, nil
}

// Eval applies expr to v (values as from encoding/json: map, slice, ...).
func Eval(v any, expr string) ([]any, error) {
    steps, err := parse(expr)
    if err != nil {
        return nil, err
    }
    cur := []any{v}
    for _, s := range steps {
        var next []any
        for _, x := range cur {
            out, err := apply(x, s)
            if err != nil {
                return nil, err
            }
            next = append(next, out...)
        }
        cur = next
    }
    return cur, nil
}

// apply executes one step. Like jq: .x on null or something missing is null.
func apply(x any, s step) ([]any, error) {
    switch s.kind {
    case field:
        if x == nil {
            return []any{nil}, nil
        }
        m, ok := x.(map[string]any)
        if !ok {
            return nil, fmt.Errorf("%w: .%s auf %T", ErrType, s.key, x)
        }
        return []any{m[s.key]}, nil
    case index:
        if x == nil {
            return []any{nil}, nil
        }
        a, ok := x.([]any)
        if !ok {
            return nil, fmt.Errorf("%w: [%d] auf %T", ErrType, s.n, x)
        }
        i := s.n
        if i < 0 {
            i += len(a) // [-1] ist das letzte Element
        }
        if i < 0 || i >= len(a) {
            return []any{nil}, nil
        }
        return []any{a[i]}, nil
    }
    switch t := x.(type) { // iter
    case []any:
        return t, nil
    case map[string]any:
        out := make([]any, 0, len(t))
        for _, k := range slices.Sorted(maps.Keys(t)) {
            out = append(out, t[k])
        }
        return out, nil
    }
    return nil, fmt.Errorf("%w: [] auf %T", ErrType, x)
}
EOF
cat > cmd/jsonq/main.go <<'EOF'
// jsonq is a mini jq: jsonq [-r] AUSDRUCK [DATEI]
// Day 15 of "Go hands-on".
package main

import (
    "encoding/json"
    "errors"
    "flag"
    "fmt"
    "io"
    "os"

    "example.com/jsonq/internal/query"
)

func main() {
    os.Exit(run(os.Args[1:], os.Stdin, os.Stdout, os.Stderr))
}

func run(args []string, stdin io.Reader, stdout, stderr io.Writer) int {
    fl := flag.NewFlagSet("jsonq", flag.ContinueOnError)
    fl.SetOutput(stderr)
    raw := fl.Bool("r", false, "Strings ohne Anführungszeichen ausgeben")
    if err := fl.Parse(args); err != nil {
        return 2
    }
    if fl.NArg() < 1 || fl.NArg() > 2 {
        fmt.Fprintln(stderr, "Aufruf: jsonq [-r] AUSDRUCK [DATEI]")
        return 2
    }
    in := stdin
    if fl.NArg() == 2 {
        f, err := os.Open(fl.Arg(1))
        if err != nil {
            fmt.Fprintln(stderr, "jsonq:", err)
            return 1
        }
        defer f.Close()
        in = f
    }

    dec := json.NewDecoder(in)
    dec.UseNumber() // 1000000 bleibt 1000000 statt 1e+06
    enc := json.NewEncoder(stdout)
    enc.SetEscapeHTML(false)
    for { // mehrere JSON-Werte hintereinander (JSON Lines) sind erlaubt
        var v any
        err := dec.Decode(&v)
        if errors.Is(err, io.EOF) {
            return 0
        }
        if err != nil {
            fmt.Fprintln(stderr, "jsonq: Eingabe:", err)
            return 1
        }
        out, err := query.Eval(v, fl.Arg(0))
        if errors.Is(err, query.ErrSyntax) {
            fmt.Fprintln(stderr, "jsonq:", err)
            return 2
        }
        if err != nil {
            fmt.Fprintln(stderr, "jsonq:", err)
            return 1
        }
        for _, x := range out {
            if s, ok := x.(string); ok && *raw {
                fmt.Fprintln(stdout, s)
                continue
            }
            _ = enc.Encode(x)
        }
    }
}
EOF
ziel
go test -run '^$' -fuzz FuzzEval -fuzztime 10s ./internal/query | tail -2

Expected (abbreviated):

0 issues.
Zeit: 26 min
PASS
ok      example.com/jsonq/internal/query    11.251s

Why? First split (parse → []step), then evaluate: each step turns a list of values into a new one – that way [] yields multiple results, and all following steps automatically run for each of them. dec.UseNumber() keeps numbers as json.Number instead of float64; otherwise 98000000 would come out as 9.8e+07.

go build -o bin/jsonq ./cmd/jsonq
cat > releases.json <<'EOF'
[{"tag_name":"v2.7.1","prerelease":false,
  "assets":[{"name":"bao_linux_amd64","size":98000000}]},
 {"tag_name":"v2.8.0-rc.1","prerelease":true,"assets":[]}]
EOF
./bin/jsonq -r '.[].tag_name' releases.json
./bin/jsonq '.[0].assets[-1]' releases.json
./bin/jsonq '.[0].assets[0].size' < releases.json
printf '{"msg":"start"}\n{"msg":"kaputt"}\n' | ./bin/jsonq -r .msg
./bin/jsonq '.[0].tag_name[0]' releases.json; echo "exit=$?"
./bin/jsonq 'tag_name' releases.json; echo "exit=$?"
diff <(./bin/jsonq '.[].assets' releases.json) \
  <(jq -c '.[].assets' releases.json) && echo "gleich wie jq"

Expected:

v2.7.1
v2.8.0-rc.1
{"name":"bao_linux_amd64","size":98000000}
98000000
start
kaputt
jsonq: typfehler: [0] auf string
exit=1
jsonq: syntaxfehler: "tag_name" muss mit . beginnen
exit=2
gleich wie jq

One difference remains: encoding/json prints map keys sorted, jq in input order. For comparisons with jq you therefore use jq -S.

Save your progress? Sign up for free

Challenge 4: envdiff – comparing .env files without revealing secrets

Time limit: 20 min · Points: 10 · Building blocks: bufio, strings, maps, sorting (Days 1, 2)

Specification

  • envfile.Parse(r) reads KEY=VALUE lines: skip blank lines and # comments, ignore a leading export, allow spaces around =.
  • Values in "…" or '…' lose the quotes and keep everything in between; without quotes, # starts a comment.
  • An invalid key (not [A-Za-z_][A-Za-z0-9_]*) or a line without =: an error with the line number (zeile 2: …).
  • envfile.Diff(a, b) returns []Change{Key, Kind, Old, New} with Added (+), Removed (-), Changed (~), sorted by key. envfile.Mask(v) reveals only the length: <6 Zeichen>, empty: "".
  • CLI: envdiff [-show] ALT NEU masks values, except with -show. Exit codes like diff: 0 = identical, 1 = differences, 2 = error.

Tests

start envdiff envfile
cat > internal/envfile/envfile_test.go <<'EOF'
package envfile

import (
    "reflect"
    "strings"
    "testing"
)

func TestParse(t *testing.T) {
    in := `# Kommentar
APP_ENV=prod

export DB_HOST = db1.lab
DB_PASS="lab pw # kein Kommentar"
TOKEN='sk-lab-1234'
PORT=8080 # Kommentar am Ende
LEER=
URL=https://x.lab/?a=b
`
    got, err := Parse(strings.NewReader(in))
    if err != nil {
        t.Fatal(err)
    }
    want := map[string]string{
        "APP_ENV": "prod", "DB_HOST": "db1.lab", "DB_PASS": "lab pw # kein Kommentar",
        "TOKEN": "sk-lab-1234", "PORT": "8080", "LEER": "", "URL": "https://x.lab/?a=b",
    }
    if !reflect.DeepEqual(got, want) {
        t.Errorf("\n got %q\nwant %q", got, want)
    }
}

func TestParseFehler(t *testing.T) {
    for _, in := range []string{"A=1\nB-C=2\n", "A=1\nnur text\n", "A=1\n1X=2\n"} {
        _, err := Parse(strings.NewReader(in))
        if err == nil || !strings.Contains(err.Error(), "zeile 2") {
            t.Errorf("Parse(%q) err = %v, will Fehler mit zeile 2", in, err)
        }
    }
}

func TestDiff(t *testing.T) {
    a := map[string]string{"A": "1", "B": "2", "C": "3"}
    b := map[string]string{"B": "2", "C": "33", "D": "4"}
    want := []Change{
        {Key: "A", Kind: Removed, Old: "1"},
        {Key: "C", Kind: Changed, Old: "3", New: "33"},
        {Key: "D", Kind: Added, New: "4"},
    }
    if got := Diff(a, b); !reflect.DeepEqual(got, want) {
        t.Errorf("\n got %+v\nwant %+v", got, want)
    }
    if got := Diff(a, a); len(got) != 0 {
        t.Errorf("Diff(a, a) = %+v, will leer", got)
    }
}

func TestMask(t *testing.T) {
    tests := map[string]string{
        "": `""`, "geheim": "<6 Zeichen>", "Grüße": "<5 Zeichen>",
    }
    for in, want := range tests {
        if got := Mask(in); got != want {
            t.Errorf("Mask(%q) = %q, will %q", in, got, want)
        }
    }
}
EOF

Sample solution

cat > internal/envfile/envfile.go <<'EOF'
// Package envfile reads .env files and compares them.
package envfile

import (
    "bufio"
    "fmt"
    "io"
    "maps"
    "regexp"
    "slices"
    "strings"
    "unicode/utf8"
)

var keyRe = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]*$`)

// Parse reads KEY=VALUE lines with # comments, "export " and quotes.
// Duplicate keys: the last one wins (as with source in the shell).
func Parse(r io.Reader) (map[string]string, error) {
    env := map[string]string{}
    sc := bufio.NewScanner(r)
    for n := 1; sc.Scan(); n++ {
        line := strings.TrimSpace(sc.Text())
        if line == "" || strings.HasPrefix(line, "#") {
            continue
        }
        line = strings.TrimPrefix(line, "export ")
        key, val, ok := strings.Cut(line, "=")
        key, val = strings.TrimSpace(key), strings.TrimSpace(val)
        if !ok || !keyRe.MatchString(key) {
            return nil, fmt.Errorf("zeile %d: erwarte KEY=VALUE, nicht %q", n, line)
        }
        env[key] = value(val)
    }
    return env, sc.Err()
}

// value removes quotes; without quotes, " #" starts a comment.
func value(v string) string {
    if len(v) >= 2 && (v[0] == '"' || v[0] == '\'') && v[len(v)-1] == v[0] {
        return v[1 : len(v)-1]
    }
    if i := strings.Index(v, " #"); i >= 0 {
        v = strings.TrimSpace(v[:i])
    }
    return v
}

// Kind is the type of a change.
type Kind string

const (
    Added   Kind = "+"
    Removed Kind = "-"
    Changed Kind = "~"
)

// Change is one difference between two files.
type Change struct {
    Key      string
    Kind     Kind
    Old, New string
}

// Diff returns all differences from a to b, sorted by key.
func Diff(a, b map[string]string) []Change {
    keys := slices.Sorted(maps.Keys(a))
    for k := range b {
        if _, ok := a[k]; !ok {
            keys = append(keys, k)
        }
    }
    slices.Sort(keys)
    var out []Change
    for _, k := range keys {
        va, inA := a[k]
        vb, inB := b[k]
        switch {
        case !inB:
            out = append(out, Change{Key: k, Kind: Removed, Old: va})
        case !inA:
            out = append(out, Change{Key: k, Kind: Added, New: vb})
        case va != vb:
            out = append(out, Change{Key: k, Kind: Changed, Old: va, New: vb})
        }
    }
    return out
}

// Mask reveals only the length of a value – secrets stay invisible.
func Mask(v string) string {
    if v == "" {
        return `""`
    }
    return fmt.Sprintf("<%d Zeichen>", utf8.RuneCountInString(v))
}
EOF
cat > cmd/envdiff/main.go <<'EOF'
// envdiff compares two .env files without revealing secrets:
// envdiff [-show] ALT NEU. Exit 0 = identical, 1 = differences, 2 = error.
// Day 15 of "Go hands-on".
package main

import (
    "flag"
    "fmt"
    "io"
    "os"

    "example.com/envdiff/internal/envfile"
)

func main() {
    os.Exit(run(os.Args[1:], os.Stdout, os.Stderr))
}

func run(args []string, stdout, stderr io.Writer) int {
    fl := flag.NewFlagSet("envdiff", flag.ContinueOnError)
    fl.SetOutput(stderr)
    show := fl.Bool("show", false, "Werte im Klartext zeigen (Vorsicht: Secrets!)")
    if err := fl.Parse(args); err != nil {
        return 2
    }
    if fl.NArg() != 2 {
        fmt.Fprintln(stderr, "Aufruf: envdiff [-show] ALT NEU")
        return 2
    }
    var envs [2]map[string]string
    for i, name := range fl.Args() {
        env, err := load(name)
        if err != nil {
            fmt.Fprintln(stderr, "envdiff:", err)
            return 2
        }
        envs[i] = env
    }
    val := envfile.Mask
    if *show {
        val = func(v string) string { return v }
    }
    changes := envfile.Diff(envs[0], envs[1])
    for _, c := range changes {
        switch c.Kind {
        case envfile.Added:
            fmt.Fprintf(stdout, "+ %s=%s\n", c.Key, val(c.New))
        case envfile.Removed:
            fmt.Fprintf(stdout, "- %s\n", c.Key)
        case envfile.Changed:
            fmt.Fprintf(stdout, "~ %s: %s -> %s\n", c.Key, val(c.Old), val(c.New))
        }
    }
    if len(changes) > 0 {
        return 1
    }
    return 0
}

func load(name string) (map[string]string, error) {
    f, err := os.Open(name)
    if err != nil {
        return nil, err
    }
    defer f.Close()
    env, err := envfile.Parse(f)
    if err != nil {
        return nil, fmt.Errorf("%s: %w", name, err)
    }
    return env, nil
}
EOF
ziel

Why? strings.Cut splits at the first =, which is why URL=https://x.lab/?a=b stays intact. The error message starts in lowercase (zeile 2, “line 2”) because the linter flags capitalized error strings (ST1005) – they are usually embedded in other messages. In main, val is a function variable: one line decides whether to mask, not every Printf.

go build -o bin/envdiff ./cmd/envdiff
printf 'APP_ENV=staging\nDB_HOST=db1.lab\nDB_PASS=lab-pw-staging\nFEATURE_X=true\n' \
  > staging.env
printf 'APP_ENV=prod\nDB_HOST=db1.lab\nDB_PASS="lab-pw-prod-2026"\nLOG_LEVEL=warn\n' \
  > prod.env
./bin/envdiff staging.env prod.env; echo "exit=$?"
./bin/envdiff -show staging.env prod.env | grep APP_ENV
./bin/envdiff prod.env prod.env; echo "exit=$?"
printf 'A=1\nkaputt\n' > bad.env; ./bin/envdiff prod.env bad.env; echo "exit=$?"

Expected:

~ APP_ENV: <7 Zeichen> -> <4 Zeichen>
~ DB_PASS: <14 Zeichen> -> <16 Zeichen>
- FEATURE_X
+ LOG_LEVEL=<4 Zeichen>
exit=1
~ APP_ENV: staging -> prod
exit=0
envdiff: bad.env: zeile 2: erwarte KEY=VALUE, nicht "kaputt"
exit=2

The passwords are lab values – even so, they don’t show up in the output. That is exactly how a diff belongs in a CI log.

Save your progress? Sign up for free

Challenge 5: certdays – how much longer is the certificate valid?

Time limit: 25 min · Points: 15 · Building blocks: crypto/x509, crypto/tls, context, httptest (Days 7, 9)

Specification

  • certs.Days(notAfter, now) returns the full days until expiry, rounded down; expired is negative (1 hour past = -1).
  • certs.FromPEM(name, data, now) reads all CERTIFICATE blocks (bundle, chain) and skips other blocks such as keys. No certificate: an error with ErrNoCert.
  • certs.FromAddr(ctx, "host:port", now) fetches the server certificate via a TLS handshake – including expired or self-signed ones, because those are exactly the ones you want to find.
  • certs.Info contains Source, Subject (CN=…), NotAfter, Days.
  • CLI: certdays [-warn 30] [-timeout 5s] ZIEL...; ZIEL (target) is an existing file or host:port. A table with TAGE ABLAUF SUBJECT QUELLE (days, expiry, subject, source), ✘ below -warn. Exit 1 if one is below -warn or unreadable; 2 = invocation.

Tests

start certdays certs
cat > internal/certs/certs_test.go <<'EOF'
package certs

import (
    "context"
    "crypto/ecdsa"
    "crypto/elliptic"
    "crypto/rand"
    "crypto/x509"
    "crypto/x509/pkix"
    "encoding/pem"
    "errors"
    "math/big"
    "net/http/httptest"
    "strings"
    "testing"
    "time"
)

var now = time.Date(2026, 10, 10, 12, 0, 0, 0, time.UTC)

// selfSigned creates a lab certificate as PEM, valid until notAfter.
func selfSigned(t *testing.T, cn string, notAfter time.Time) []byte {
    t.Helper()
    key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
    if err != nil {
        t.Fatal(err)
    }
    tmpl := &x509.Certificate{
        SerialNumber: big.NewInt(1),
        Subject:      pkix.Name{CommonName: cn},
        NotBefore:    now.AddDate(0, -1, 0),
        NotAfter:     notAfter,
    }
    der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key)
    if err != nil {
        t.Fatal(err)
    }
    return pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der})
}

func TestDays(t *testing.T) {
    tests := []struct {
        notAfter time.Time
        want     int
    }{
        {now.Add(10*24*time.Hour + time.Hour), 10},
        {now.Add(23 * time.Hour), 0},
        {now.Add(-time.Hour), -1}, // abgelaufen: negativ
    }
    for _, tt := range tests {
        if got := Days(tt.notAfter, now); got != tt.want {
            t.Errorf("Days(%v) = %d, will %d", tt.notAfter, got, tt.want)
        }
    }
}

func TestFromPEM(t *testing.T) {
    data := append(selfSigned(t, "a.lab", now.AddDate(0, 0, 30)),
        selfSigned(t, "b.lab", now.Add(-48*time.Hour))...)
    infos, err := FromPEM("bundle.pem", data, now)
    if err != nil {
        t.Fatal(err)
    }
    if len(infos) != 2 {
        t.Fatalf("%d Zertifikate, will 2", len(infos))
    }
    if infos[0].Subject != "CN=a.lab" || infos[0].Days != 30 ||
        infos[1].Days != -2 || infos[1].Source != "bundle.pem" {
        t.Errorf("infos = %+v", infos)
    }
}

func TestFromPEMOhneZertifikat(t *testing.T) {
    _, err := FromPEM("x.pem", []byte("kein PEM"), now)
    if !errors.Is(err, ErrNoCert) {
        t.Errorf("err = %v, will ErrNoCert", err)
    }
}

func TestFromAddr(t *testing.T) {
    srv := httptest.NewTLSServer(nil) // Testzertifikat von Go, lange gültig
    defer srv.Close()
    addr := strings.TrimPrefix(srv.URL, "https://")
    ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
    defer cancel()
    infos, err := FromAddr(ctx, addr, now)
    if err != nil {
        t.Fatal(err)
    }
    if len(infos) != 1 || infos[0].Days < 365 || infos[0].Source != addr {
        t.Errorf("infos = %+v", infos)
    }
}
EOF

The test creates its certificates itself (ECDSA P-256, self-signed) – no files, no network. httptest.NewTLSServer provides a real TLS server with Go’s own test certificate.

Sample solution

cat > internal/certs/certs.go <<'EOF'
// Package certs reads certificates from PEM files or from TLS servers
// and calculates the remaining days.
package certs

import (
    "context"
    "crypto/tls"
    "crypto/x509"
    "encoding/pem"
    "errors"
    "fmt"
    "math"
    "net"
    "time"
)

// ErrNoCert reports a file without a CERTIFICATE block.
var ErrNoCert = errors.New("kein Zertifikat gefunden")

// Info describes a certificate.
type Info struct {
    Source   string // Datei oder host:port
    Subject  string
    NotAfter time.Time
    Days     int // volle Tage bis Ablauf, negativ = abgelaufen
}

// Days returns the full days from now until notAfter (rounded down).
func Days(notAfter, now time.Time) int {
    return int(math.Floor(notAfter.Sub(now).Hours() / 24))
}

func info(src string, c *x509.Certificate, now time.Time) Info {
    return Info{Source: src, Subject: c.Subject.String(), NotAfter: c.NotAfter,
        Days: Days(c.NotAfter, now)}
}

// FromPEM reads all certificates from data (e.g. a chain or a bundle).
func FromPEM(name string, data []byte, now time.Time) ([]Info, error) {
    var out []Info
    for {
        var b *pem.Block
        b, data = pem.Decode(data)
        if b == nil {
            break
        }
        if b.Type != "CERTIFICATE" {
            continue // z. B. PRIVATE KEY im selben File
        }
        c, err := x509.ParseCertificate(b.Bytes)
        if err != nil {
            return nil, fmt.Errorf("%s: %w", name, err)
        }
        out = append(out, info(name, c, now))
    }
    if len(out) == 0 {
        return nil, fmt.Errorf("%s: %w", name, ErrNoCert)
    }
    return out, nil
}

// FromAddr fetches the server certificate from addr (host:port).
func FromAddr(ctx context.Context, addr string, now time.Time) ([]Info, error) {
    host, _, err := net.SplitHostPort(addr)
    if err != nil {
        return nil, err
    }
    d := tls.Dialer{Config: &tls.Config{
        ServerName: host,
        // Read only: expired or self-signed certificates should be
        // reported too. No data is sent.
        InsecureSkipVerify: true,
    }}
    conn, err := d.DialContext(ctx, "tcp", addr)
    if err != nil {
        return nil, err
    }
    defer conn.Close()
    state := conn.(*tls.Conn).ConnectionState()
    if len(state.PeerCertificates) == 0 {
        return nil, fmt.Errorf("%s: %w", addr, ErrNoCert)
    }
    return []Info{info(addr, state.PeerCertificates[0], now)}, nil
}
EOF
cat > cmd/certdays/main.go <<'EOF'
// certdays shows how much longer certificates are valid:
// certdays [-warn 30] DATEI.pem|host:port...
// Exit 1 if one is below -warn days or unreadable.
// Day 15 of "Go hands-on".
package main

import (
    "context"
    "flag"
    "fmt"
    "io"
    "os"
    "os/signal"
    "text/tabwriter"
    "time"

    "example.com/certdays/internal/certs"
)

func main() {
    ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
    defer stop()
    os.Exit(run(ctx, os.Args[1:], time.Now(), os.Stdout, os.Stderr))
}

func run(ctx context.Context, args []string, now time.Time,
    stdout, stderr io.Writer) int {
    fl := flag.NewFlagSet("certdays", flag.ContinueOnError)
    fl.SetOutput(stderr)
    warn := fl.Int("warn", 30, "Exit 1 unter so vielen Resttagen")
    timeout := fl.Duration("timeout", 5*time.Second, "Timeout pro Server")
    if err := fl.Parse(args); err != nil {
        return 2
    }
    if fl.NArg() == 0 {
        fmt.Fprintln(stderr, "Aufruf: certdays [-warn 30] DATEI.pem|host:port...")
        return 2
    }
    code := 0
    tw := tabwriter.NewWriter(stdout, 0, 4, 2, ' ', 0)
    fmt.Fprintln(tw, "TAGE\tABLAUF\tSUBJECT\tQUELLE")
    for _, target := range fl.Args() {
        infos, err := load(ctx, target, now, *timeout)
        if err != nil {
            fmt.Fprintln(stderr, "certdays:", err)
            code = 1
            continue
        }
        for _, i := range infos {
            mark := ""
            if i.Days < *warn {
                mark, code = " ✘", 1
            }
            fmt.Fprintf(tw, "%d%s\t%s\t%s\t%s\n", i.Days, mark,
                i.NotAfter.Format(time.DateOnly), i.Subject, i.Source)
        }
    }
    _ = tw.Flush()
    return code
}

// load treats an existing file as PEM, everything else as host:port.
func load(ctx context.Context, target string, now time.Time,
    timeout time.Duration) ([]certs.Info, error) {
    if data, err := os.ReadFile(target); err == nil {
        return certs.FromPEM(target, data, now)
    }
    ctx, cancel := context.WithTimeout(ctx, timeout)
    defer cancel()
    return certs.FromAddr(ctx, target, now)
}
EOF
ziel

Why? now is a parameter instead of time.Now() inside the package – that is the only way to make the tests reproducible. math.Floor also rounds negative values down; an int(...) alone would turn -0.04 days into 0 and report an expired certificate as valid.

Security: InsecureSkipVerify is acceptable here because the tool only reads the certificate and sends no data. In any client that exchanges data, it is off-limits (Day 8, Enterprise Note).

go build -o bin/certdays ./cmd/certdays
openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -nodes \
  -days 7 -subj /CN=lab.local -keyout /dev/null -out lab.pem 2>/dev/null
./bin/certdays lab.pem go.dev:443 kubernetes.io:443; echo "exit=$?"
./bin/certdays -warn 3 lab.pem; echo "exit=$?"
./bin/certdays -timeout 1s 127.0.0.1:1 go.mod; echo "exit=$?"

Expected (abbreviated, dates change):

TAGE  ABLAUF      SUBJECT           QUELLE
6 ✘   2026-10-17  CN=lab.local      lab.pem
70    2026-12-20  CN=go.dev         go.dev:443
31    2026-11-10  CN=kubernetes.io  kubernetes.io:443
exit=1
TAGE  ABLAUF      SUBJECT       QUELLE
6     2026-10-17  CN=lab.local  lab.pem
exit=0
certdays: dial tcp 127.0.0.1:1: connect: connection refused
certdays: go.mod: kein Zertifikat gefunden
TAGE  ABLAUF  SUBJECT  QUELLE
exit=1

Issued for seven days, reported as six: the certificate is already a few seconds old, and Days rounds down. For alerts, that is the right direction.

Save your progress? Sign up for free

Challenge 6: logtail – tail -F without fsnotify

Time limit: 30 min · Points: 15 · Building blocks: io, os.FileInfo, tickers, context, race detector (Days 6, 8)

Specification

  • tail.Last(path, n) returns the last n lines and the byte offset after them – with constant memory, even for large files.
  • tail.Follow(ctx, path, off, every, out) checks the file every every and writes each new, complete line (with \n) to out. A half line waits until the rest of it arrives.
  • Truncate (file smaller than the offset, e.g. logrotate with copytruncate): read from the start.
  • Rotation (a different file now sits under the name, os.SameFile): first read the rest of the old file, then the new one from the beginning.
  • If ctx ends, Follow returns nil. CLI: logtail [-n 10] [-i 250ms] DATEI; Ctrl+C or SIGTERM ends with exit 0, error 1, invocation 2.

Tests

start logtail tail
cat > internal/tail/tail_test.go <<'EOF'
package tail

import (
    "bytes"
    "context"
    "os"
    "path/filepath"
    "slices"
    "strings"
    "sync"
    "testing"
    "time"
)

// syncBuf is a writer that the test and the Follow goroutine can share safely.
type syncBuf struct {
    mu sync.Mutex
    b  bytes.Buffer
}

func (s *syncBuf) Write(p []byte) (int, error) {
    s.mu.Lock()
    defer s.mu.Unlock()
    return s.b.Write(p)
}

func (s *syncBuf) String() string {
    s.mu.Lock()
    defer s.mu.Unlock()
    return s.b.String()
}

// waitFor waits up to 2 s until out ends with suffix.
func waitFor(t *testing.T, out *syncBuf, suffix string) {
    t.Helper()
    for range 200 {
        if strings.HasSuffix(out.String(), suffix) {
            return
        }
        time.Sleep(10 * time.Millisecond)
    }
    t.Fatalf("Ausgabe endet nicht mit %q:\n%s", suffix, out.String())
}

func appendTo(t *testing.T, path, s string) {
    t.Helper()
    f, err := os.OpenFile(path, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0o644)
    if err != nil {
        t.Fatal(err)
    }
    defer f.Close()
    if _, err := f.WriteString(s); err != nil {
        t.Fatal(err)
    }
}

func TestLast(t *testing.T) {
    path := filepath.Join(t.TempDir(), "app.log")
    appendTo(t, path, "a\nb\nc\nd\ne\n")
    lines, off, err := Last(path, 3)
    if err != nil {
        t.Fatal(err)
    }
    if !slices.Equal(lines, []string{"c", "d", "e"}) || off != 10 {
        t.Errorf("Last = %q, %d; will [c d e], 10", lines, off)
    }
}

func TestFollow(t *testing.T) {
    path := filepath.Join(t.TempDir(), "app.log")
    appendTo(t, path, "alt\n")
    ctx, cancel := context.WithCancel(context.Background())
    out := &syncBuf{}
    done := make(chan error, 1)
    go func() { done <- Follow(ctx, path, 4, 10*time.Millisecond, out) }()

    appendTo(t, path, "eins\nzw")
    time.Sleep(50 * time.Millisecond) // halbe Zeile darf noch nicht erscheinen
    if got := out.String(); got != "eins\n" {
        t.Errorf("nach halber Zeile: %q", got)
    }
    appendTo(t, path, "ei\n")
    waitFor(t, out, "eins\nzwei\n")

    // copytruncate: the file gets smaller
    if err := os.WriteFile(path, []byte("neu\n"), 0o644); err != nil {
        t.Fatal(err)
    }
    waitFor(t, out, "zwei\nneu\n")

    // Rotation: rename the old file, create a new one
    appendTo(t, path, "letzte alte\n")
    if err := os.Rename(path, path+".1"); err != nil {
        t.Fatal(err)
    }
    appendTo(t, path, "rotiert\n")
    waitFor(t, out, "neu\nletzte alte\nrotiert\n")

    cancel()
    if err := <-done; err != nil {
        t.Errorf("Follow nach cancel: %v", err)
    }
}
EOF

syncBuf is necessary because Follow writes in its own goroutine while the test reads – a bare bytes.Buffer would be a data race, and ziel runs with -race.

Sample solution

cat > internal/tail/tail.go <<'EOF'
// Package tail follows a log file like tail -F – via polling, without fsnotify.
package tail

import (
    "bufio"
    "bytes"
    "context"
    "io"
    "os"
    "time"
)

// Last returns the last n lines of path and the byte offset after them.
func Last(path string, n int) ([]string, int64, error) {
    f, err := os.Open(path)
    if err != nil {
        return nil, 0, err
    }
    defer f.Close()
    info, err := f.Stat()
    if err != nil {
        return nil, 0, err
    }
    var ring []string // höchstens n Zeilen im Speicher, auch bei GB-Logs
    sc := bufio.NewScanner(io.LimitReader(f, info.Size()))
    for sc.Scan() {
        ring = append(ring, sc.Text())
        if len(ring) > n {
            ring = ring[1:]
        }
    }
    return ring, info.Size(), sc.Err()
}

// follower remembers the open file, the position and a started line.
type follower struct {
    path    string
    f       *os.File
    info    os.FileInfo
    off     int64
    partial []byte
    out     io.Writer
}

// Follow writes every new, complete line from offset off to out
// until ctx ends. Detects truncate (file smaller) and rotation (new file).
func Follow(ctx context.Context, path string, off int64, every time.Duration,
    out io.Writer) error {
    fw := &follower{path: path, off: off, out: out}
    if err := fw.open(); err != nil {
        return err
    }
    defer func() { fw.f.Close() }()
    t := time.NewTicker(every)
    defer t.Stop()
    for {
        if err := fw.read(); err != nil {
            return err
        }
        select {
        case <-ctx.Done():
            return nil // Strg+C ist kein Fehler
        case <-t.C:
        }
        cur, err := os.Stat(path)
        switch {
        case err != nil: // gerade rotiert, neue Datei fehlt noch
        case !os.SameFile(fw.info, cur): // Rotation: Rest lesen, neu öffnen
            if err := fw.read(); err != nil {
                return err
            }
            fw.f.Close()
            fw.off, fw.partial = 0, nil
            if err := fw.open(); err != nil {
                return err
            }
        case cur.Size() < fw.off: // copytruncate: von vorn
            fw.off, fw.partial = 0, nil
        }
    }
}

func (fw *follower) open() error {
    f, err := os.Open(fw.path)
    if err != nil {
        return err
    }
    info, err := f.Stat()
    if err != nil {
        f.Close()
        return err
    }
    fw.f, fw.info = f, info
    return nil
}

// read reads everything from fw.off on and outputs only lines with \n.
func (fw *follower) read() error {
    data, err := io.ReadAll(io.NewSectionReader(fw.f, fw.off, 1<<62))
    if err != nil {
        return err
    }
    fw.off += int64(len(data))
    data = append(fw.partial, data...)
    end := bytes.LastIndexByte(data, '\n') + 1
    if _, err := fw.out.Write(data[:end]); err != nil {
        return err
    }
    fw.partial = append([]byte(nil), data[end:]...)
    return nil
}
EOF
cat > cmd/logtail/main.go <<'EOF'
// logtail shows the last lines of a file and follows it like tail -F:
// logtail [-n 10] [-i 250ms] DATEI
// Day 15 of "Go hands-on".
package main

import (
    "context"
    "flag"
    "fmt"
    "io"
    "os"
    "os/signal"
    "syscall"
    "time"

    "example.com/logtail/internal/tail"
)

func main() {
    ctx, stop := signal.NotifyContext(context.Background(),
        os.Interrupt, syscall.SIGTERM)
    defer stop()
    os.Exit(run(ctx, os.Args[1:], os.Stdout, os.Stderr))
}

func run(ctx context.Context, args []string, stdout, stderr io.Writer) int {
    fl := flag.NewFlagSet("logtail", flag.ContinueOnError)
    fl.SetOutput(stderr)
    n := fl.Int("n", 10, "so viele Zeilen zuerst zeigen")
    every := fl.Duration("i", 250*time.Millisecond, "Prüfintervall")
    if err := fl.Parse(args); err != nil {
        return 2
    }
    if fl.NArg() != 1 || *n < 0 || *every <= 0 {
        fmt.Fprintln(stderr, "Aufruf: logtail [-n 10] [-i 250ms] DATEI")
        return 2
    }
    path := fl.Arg(0)
    lines, off, err := tail.Last(path, *n)
    if err != nil {
        fmt.Fprintln(stderr, "logtail:", err)
        return 1
    }
    for _, l := range lines {
        fmt.Fprintln(stdout, l)
    }
    if err := tail.Follow(ctx, path, off, *every, stdout); err != nil {
        fmt.Fprintln(stderr, "logtail:", err)
        return 1
    }
    return 0
}
EOF
ziel
go test -race -count=30 ./internal/tail

Expected (abbreviated):

0 issues.
Zeit: 28 min
ok      example.com/logtail/internal/tail   4.160s

Why? os.SameFile compares device and inode – that is how Follow detects a new file under the old name without looking at the content. The old file descriptor stays valid after mv; that is why the rest can still be read. -count=30 repeats the timing-dependent test – that way a flaky test shows up before your colleague runs into it.

go build -o bin/logtail ./cmd/logtail
for i in 1 2 3 4 5; do echo "boot $i" >> app.log; done
./bin/logtail -n 2 app.log > out.txt & pid=$!
sleep 0.5; echo "request 1" >> app.log; sleep 0.5
echo "nach truncate" > app.log; sleep 0.5
mv app.log app.log.1; echo "neue Datei" > app.log; sleep 0.5
kill -INT $pid; wait $pid; echo "exit=$?"
cat out.txt

Expected:

exit=0
boot 4
boot 5
request 1
nach truncate
neue Datei

Save your progress? Sign up for free

Challenge 7: llm-commit – a commit message from the local model

Time limit: 30 min · Points: 20 · Building blocks: net/http, JSON, os/exec, validating and repairing (Days 5, 7, 12)

Specification

  • commit.Client{BaseURL, Model, Key, HTTP} sends POST {BaseURL}/chat/completions (OpenAI-compatible, as on Day 12) with a system prompt and the diff; Authorization: Bearer … only if Key is set.
  • commit.Clean(s) removes Markdown fences, surrounding quotes, whitespace and double blank lines, and puts exactly one blank line between subject and body.
  • commit.Valid(msg) requires a subject following Conventional Commits (feat, fix, docs, refactor, test, chore, build, ci, perf, style, optionally (scope) and !) with at most 72 characters.
  • Client.Message(ctx, diff) cleans and checks every answer. If it is invalid, the model gets the error as a new message – at most attempts = 3 requests in total. commit.Truncate(diff, limit) cuts at a line boundary.
  • CLI: llm-commit [-stdin] [-max 12000] reads git diff --cached (or stdin), uses LLM_BASE_URL, LLM_MODEL, LLM_API_KEY as on Day 12, and prints only the message on stdout. Exit 1 on an empty diff or an LLM error, 2 = invocation.

Tests

start llm-commit commit
cat > internal/commit/commit_test.go <<'EOF'
package commit

import (
    "context"
    "encoding/json"
    "fmt"
    "net/http"
    "net/http/httptest"
    "strings"
    "sync/atomic"
    "testing"
)

func TestClean(t *testing.T) {
    tests := []struct{ in, want string }{
        {"feat: neu", "feat: neu"},
        {"```\nfix(api): Timeout setzen\n```", "fix(api): Timeout setzen"},
        {"\"docs: README\"", "docs: README"},
        {"feat: x\nBody direkt", "feat: x\n\nBody direkt"},
        {"  chore: y  \n\n\n\nmehr  ", "chore: y\n\nmehr"},
    }
    for _, tt := range tests {
        if got := Clean(tt.in); got != tt.want {
            t.Errorf("Clean(%q) = %q, will %q", tt.in, got, tt.want)
        }
    }
}

func TestValid(t *testing.T) {
    ok := []string{"feat: neu", "fix(api)!: Bruch", "ci(go): Lint in CI"}
    bad := []string{"Added stuff", "feat:ohne Leerzeichen", "feat: " +
        strings.Repeat("x", 70), "", "feature: falscher Typ"}
    for _, s := range ok {
        if err := Valid(s); err != nil {
            t.Errorf("Valid(%q) = %v", s, err)
        }
    }
    for _, s := range bad {
        if Valid(s) == nil {
            t.Errorf("Valid(%q) = nil, will Fehler", s)
        }
    }
}

func TestTruncate(t *testing.T) {
    diff := strings.Repeat("+zeile\n", 100) // 700 Bytes
    got, cut := Truncate(diff, 50)
    if !cut || len(got) > 50 || !strings.HasSuffix(got, "+zeile\n") {
        t.Errorf("Truncate = %q, %v", got, cut)
    }
    if got, cut := Truncate("kurz\n", 50); cut || got != "kurz\n" {
        t.Errorf("kurzer Diff verändert: %q, %v", got, cut)
    }
}

// fakeLLM answers with answers one after another and checks every request.
func fakeLLM(t *testing.T, answers ...string) (*Client, *atomic.Int32) {
    t.Helper()
    var calls atomic.Int32
    srv := httptest.NewServer(http.HandlerFunc(
        func(w http.ResponseWriter, r *http.Request) {
            n := calls.Add(1)
            if r.URL.Path != "/chat/completions" ||
                r.Header.Get("Authorization") != "Bearer sk-lab-1234" {
                t.Errorf("Anfrage: %s %q", r.URL.Path, r.Header.Get("Authorization"))
            }
            var req request
            if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
                t.Error(err)
            }
            last := req.Messages[len(req.Messages)-1].Content
            if req.Model != "lab-model" || (n == 1 && !strings.Contains(last, "+x")) {
                t.Errorf("Request %d: model=%q, zuletzt %q", n, req.Model, last)
            }
            a, _ := json.Marshal(answers[min(int(n), len(answers))-1])
            fmt.Fprintf(w, `{"choices":[{"message":{"role":"assistant",`+
                `"content":%s}}]}`, a)
        }))
    t.Cleanup(srv.Close)
    return &Client{BaseURL: srv.URL, Model: "lab-model", Key: "sk-lab-1234",
        HTTP: srv.Client()}, &calls
}

func TestMessage(t *testing.T) {
    c, calls := fakeLLM(t, "```\nfeat(api): /healthz ergänzen\n```")
    msg, err := c.Message(context.Background(), "+x\n")
    if err != nil || msg != "feat(api): /healthz ergänzen" || calls.Load() != 1 {
        t.Errorf("Message = %q, %v (%d Aufrufe)", msg, err, calls.Load())
    }
}

func TestMessageReparatur(t *testing.T) {
    c, calls := fakeLLM(t, "Added a health endpoint", "feat: Health-Endpunkt")
    msg, err := c.Message(context.Background(), "+x\n")
    if err != nil || msg != "feat: Health-Endpunkt" || calls.Load() != 2 {
        t.Errorf("Message = %q, %v (%d Aufrufe)", msg, err, calls.Load())
    }
}

func TestMessageGibtAuf(t *testing.T) {
    c, calls := fakeLLM(t, "Quatsch")
    if _, err := c.Message(context.Background(), "+x\n"); err == nil ||
        calls.Load() != attempts {
        t.Errorf("err = %v nach %d Aufrufen, will Fehler nach %d", err,
            calls.Load(), attempts)
    }
}
EOF

fakeLLM is an httptest server that returns predefined answers one after another and checks every request – you only need the real model at the very end.

Sample solution

cat > internal/commit/commit.go <<'EOF'
// Package commit has an LLM write a commit message from a git diff.
package commit

import (
    "bytes"
    "context"
    "encoding/json"
    "fmt"
    "io"
    "net/http"
    "regexp"
    "strings"
)

const system = `Du schreibst Commit-Messages im Format Conventional Commits.
Erste Zeile: typ(scope): beschreibung – höchstens 72 Zeichen, Imperativ.
Typen: feat, fix, docs, refactor, test, chore, build, ci, perf, style.
Danach optional eine Leerzeile und 1-3 Zeilen Begründung.
Antworte nur mit der Commit-Message, ohne Erklärungen und ohne Markdown.`

var subjectRe = regexp.MustCompile(
    `^(feat|fix|docs|refactor|test|chore|build|ci|perf|style)(\([\w./-]+\))?!?: \S`)

// Valid checks the first line against Conventional Commits.
func Valid(msg string) error {
    subject, _, _ := strings.Cut(msg, "\n")
    if !subjectRe.MatchString(subject) {
        return fmt.Errorf("betreff %q ist kein Conventional Commit", subject)
    }
    if n := len([]rune(subject)); n > 72 {
        return fmt.Errorf("betreff hat %d Zeichen, erlaubt sind 72", n)
    }
    return nil
}

// Clean removes Markdown fences, quotes and superfluous blank lines
// and puts exactly one blank line between subject and body.
func Clean(s string) string {
    var lines []string
    for l := range strings.Lines(strings.Trim(strings.TrimSpace(s), `"`)) {
        l = strings.TrimSpace(l)
        if strings.HasPrefix(l, "```") {
            continue
        }
        if l == "" && (len(lines) == 0 || lines[len(lines)-1] == "") {
            continue // keine doppelten Leerzeilen
        }
        lines = append(lines, l)
    }
    if len(lines) > 1 && lines[1] != "" {
        lines = append(lines[:1], append([]string{""}, lines[1:]...)...)
    }
    return strings.TrimSpace(strings.Join(lines, "\n"))
}

// Truncate cuts diff at a line boundary to at most limit bytes.
func Truncate(diff string, limit int) (string, bool) {
    if len(diff) <= limit {
        return diff, false
    }
    cut := diff[:limit]
    if i := strings.LastIndexByte(cut, '\n'); i >= 0 {
        cut = cut[:i+1]
    }
    return cut, true
}

type message struct {
    Role    string `json:"role"`
    Content string `json:"content"`
}

type request struct {
    Model       string    `json:"model"`
    Messages    []message `json:"messages"`
    Temperature float64   `json:"temperature"`
}

// Client talks to an OpenAI-compatible chat API (Ollama, vLLM, Mistral).
type Client struct {
    BaseURL, Model, Key string
    HTTP                *http.Client
}

// attempts: how many times the model may repair an invalid answer.
const attempts = 3

// Message generates a commit message. If an answer is invalid, the model
// gets the error as feedback and another attempt.
func (c *Client) Message(ctx context.Context, diff string) (string, error) {
    msgs := []message{
        {Role: "system", Content: system},
        {Role: "user", Content: "Schreibe die Commit-Message für:\n\n" + diff},
    }
    var err error
    for range attempts {
        var answer string
        answer, err = c.chat(ctx, msgs)
        if err != nil {
            return "", err
        }
        msg := Clean(answer)
        if err = Valid(msg); err == nil {
            return msg, nil
        }
        msgs = append(msgs, message{Role: "assistant", Content: answer},
            message{Role: "user", Content: "Ungültig: " + err.Error() +
                ". Antworte nur mit der korrigierten Commit-Message."})
    }
    return "", err
}

func (c *Client) chat(ctx context.Context, msgs []message) (string, error) {
    body, err := json.Marshal(request{Model: c.Model, Messages: msgs,
        Temperature: 0.2})
    if err != nil {
        return "", err
    }
    req, err := http.NewRequestWithContext(ctx, http.MethodPost,
        c.BaseURL+"/chat/completions", bytes.NewReader(body))
    if err != nil {
        return "", err
    }
    req.Header.Set("Content-Type", "application/json")
    if c.Key != "" {
        req.Header.Set("Authorization", "Bearer "+c.Key)
    }
    resp, err := c.HTTP.Do(req)
    if err != nil {
        return "", err
    }
    defer resp.Body.Close()
    if resp.StatusCode != http.StatusOK {
        msg, _ := io.ReadAll(io.LimitReader(resp.Body, 512))
        return "", fmt.Errorf("LLM: %s: %s", resp.Status, bytes.TrimSpace(msg))
    }
    var out struct {
        Choices []struct {
            Message message `json:"message"`
        } `json:"choices"`
    }
    if err := json.NewDecoder(resp.Body).Decode(&out); err != nil {
        return "", err
    }
    if len(out.Choices) == 0 {
        return "", fmt.Errorf("LLM: Antwort ohne choices")
    }
    return out.Choices[0].Message.Content, nil
}
EOF
cat > cmd/llm-commit/main.go <<'EOF'
// llm-commit writes a commit message from the staged diff via an LLM:
// git add -p && llm-commit | git commit -F -
// Day 15 of "Go hands-on".
package main

import (
    "cmp"
    "context"
    "flag"
    "fmt"
    "io"
    "net/http"
    "os"
    "os/exec"
    "os/signal"
    "strings"
    "time"

    "example.com/llm-commit/internal/commit"
)

func main() {
    ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
    defer stop()
    os.Exit(run(ctx, os.Args[1:], os.Getenv, os.Stdin, os.Stdout, os.Stderr))
}

func run(ctx context.Context, args []string, getenv func(string) string,
    stdin io.Reader, stdout, stderr io.Writer) int {
    fl := flag.NewFlagSet("llm-commit", flag.ContinueOnError)
    fl.SetOutput(stderr)
    fromStdin := fl.Bool("stdin", false, "Diff von stdin statt git diff --cached")
    limit := fl.Int("max", 12000, "höchstens so viele Bytes Diff ans Modell")
    timeout := fl.Duration("timeout", 2*time.Minute, "Gesamtbudget")
    if err := fl.Parse(args); err != nil || fl.NArg() != 0 {
        fmt.Fprintln(stderr, "Aufruf: llm-commit [-stdin] [-max 12000]")
        return 2
    }
    ctx, cancel := context.WithTimeout(ctx, *timeout)
    defer cancel()

    var diff []byte
    var err error
    if *fromStdin {
        diff, err = io.ReadAll(stdin)
    } else {
        diff, err = exec.CommandContext(ctx, "git", "diff", "--cached",
            "--no-color").Output()
    }
    if err != nil {
        fmt.Fprintln(stderr, "llm-commit: diff lesen:", err)
        return 1
    }
    if strings.TrimSpace(string(diff)) == "" {
        fmt.Fprintln(stderr, "llm-commit: nichts gestaged (git add vergessen?)")
        return 1
    }
    d, cut := commit.Truncate(string(diff), *limit)
    if cut {
        fmt.Fprintf(stderr, "llm-commit: Diff auf %d Bytes gekürzt\n", len(d))
    }

    c := &commit.Client{
        BaseURL: cmp.Or(getenv("LLM_BASE_URL"), "http://127.0.0.1:11434/v1"),
        Model:   cmp.Or(getenv("LLM_MODEL"), "ministral-3:3b"),
        Key:     getenv("LLM_API_KEY"),
        HTTP:    &http.Client{},
    }
    msg, err := c.Message(ctx, d)
    if err != nil {
        fmt.Fprintln(stderr, "llm-commit:", err)
        return 1
    }
    fmt.Fprintln(stdout, msg)
    return 0
}
EOF
ziel

Why? A 3B model doesn’t always stick to formatting rules. Instead of hoping for luck, code checks the answer, and the error text goes back to the model as feedback – the same pattern as with the JSON output on Day 12. strings.Lines (Go 1.24) yields the lines as an iterator, including \n.

Now against Ollama – in a throwaway repo, so your real Git stays untouched:

go build -o bin/llm-commit ./cmd/llm-commit
cd "$(mktemp -d)" && git init -q
cp ~/go-lab/tag15-portwait/cmd/portwait/main.go .
git add . && git commit -qm "chore: start"
perl -pi -e 's/30\*time.Second/60*time.Second/' main.go && git add main.go
~/go-lab/tag15-llm-commit/bin/llm-commit
~/go-lab/tag15-llm-commit/bin/llm-commit | git commit -q -F - && git log --oneline
~/go-lab/tag15-llm-commit/bin/llm-commit; echo "exit=$?"
cd ~/go-lab/tag15-llm-commit

Expected (wording varies from run to run):

fix(portwait): erhöhe timeout auf 60 Sekunden für bessere Stabilität
9732fae fix(main): timeout von 30s auf 60s erhöhen
f998523 chore: start
llm-commit: nichts gestaged (git add vergessen?)
exit=1

Security: A diff can contain secrets. Only send it to a local model or to an API your employer has approved – and run a scanner such as secretscan from Appendix B over it first.

Save your progress? Sign up for free

Scoring

Full points if ziel reports green within the time limit; half points up to double the time; none after that.

Challenge Time limit Points Achieved
1 portwait 20 min 10
2 dupfind 30 min 15
3 jsonq 30 min 15
4 envdiff 20 min 10
5 certdays 25 min 15
6 logtail 30 min 15
7 llm-commit 30 min 20
Total 185 min 100

From 70 points on, you are competition-ready for the final exam (Appendix B). For every missed time, note in one sentence what held you up – usually it is the same topic, and then you know which day to repeat.

Checkpoint

#!/usr/bin/env bash
check() { if eval "$2" >/dev/null 2>&1; then echo "✔ $1"; else echo "✘ $1"; fi; }
for d in ~/go-lab/tag15-*/; do
  t=$(basename "$d"); t=${t#tag15-}
  check "$t: fmt, vet, Tests mit -race, Lint" "cd $d && test -z \"\$(gofmt -l .)\" \
    && go vet ./... && go test -race -count=1 ./... && ~/go-lab/bin/lint run ./..."
done
b=~/go-lab/tag15
check "portwait: Exit 1 bei Timeout" \
  "$b-portwait/bin/portwait -timeout 300ms 127.0.0.1:1; test \$? -eq 1"
check "jsonq wie jq" "diff <($b-jsonq/bin/jsonq '.[0]' $b-jsonq/releases.json) \
  <(jq -cS '.[0]' $b-jsonq/releases.json)"
check "envdiff: Exit 0 bei gleichen Dateien" \
  "$b-envdiff/bin/envdiff $b-envdiff/prod.env $b-envdiff/prod.env"
check "certdays: lab.pem unter 30 Tagen" \
  "$b-certdays/bin/certdays $b-certdays/lab.pem; test \$? -eq 1"
check "llm-commit: Exit 2 bei falschem Aufruf" \
  "$b-llm-commit/bin/llm-commit extra; test \$? -eq 2"

Expected:

✔ certdays: fmt, vet, Tests mit -race, Lint
✔ dupfind: fmt, vet, Tests mit -race, Lint
✔ envdiff: fmt, vet, Tests mit -race, Lint
✔ jsonq: fmt, vet, Tests mit -race, Lint
✔ llm-commit: fmt, vet, Tests mit -race, Lint
✔ logtail: fmt, vet, Tests mit -race, Lint
✔ portwait: fmt, vet, Tests mit -race, Lint
✔ portwait: Exit 1 bei Timeout
✔ jsonq wie jq
✔ envdiff: Exit 0 bei gleichen Dateien
✔ certdays: lab.pem unter 30 Tagen
✔ llm-commit: Exit 2 bei falschem Aufruf

Challenge

Freestyle without a time limit: using two of your new tools, print only the paths of the duplicate group that wastes the most space – without jq.

Hint: dupfind already sorts by waste, and jsonq reads stdin.

Solution

cd ~/go-lab/tag15-dupfind
./bin/dupfind -json demo | ../tag15-jsonq/bin/jsonq -r '.[0].Paths[]'

Expected:

demo/sub/w2
demo/w1

Small tools that speak JSON and have clean exit codes compose themselves into pipes – that is the Unix idea, and Go delivers it as static binaries.

Save your progress? Sign up for free

Enterprise Note

  • A specification plus tests before the code is the best assignment in a team as well – for colleagues as for AI assistants: the tests are the contract, ziel the acceptance check in CI.
  • portwait replaces shell loops in entrypoints; in Kubernetes, however, dependencies belong in readiness probes and the app’s retries, not in init containers that wait forever.
  • certdays is a good ad-hoc check; for permanent monitoring use probe_ssl_earliest_cert_expiry from the Prometheus Blackbox Exporter, and cert-manager renews before anyone has to warn.
  • With copytruncate, logtail loses lines written between the copy and the truncate; in containers, logs belong on stdout, and Fluent Bit or Vector take care of collecting them.
  • LLM tools in the company repo: only approved models, check diffs for secrets beforehand, always have a human review the result – the model suggests, you commit.