018 Project 18: Go Workout - 200 Ten-Minute Exercises
018 Go Workout: 200 Ten-Minute Exercises
This chapter uses a short-exercise format inspired by workout-style learning books: small tasks, tight scope, immediate practice.
How to Use
- Spend 10 minutes per exercise.
- Do not copy old answers.
- Prefer standard library first.
- After every 10 exercises, write a short reflection.
10-minute loop
read task -> code -> run -> test edge case -> note takeaway
Foundation Warmup (1-20)
- Parse two integers from CLI args and print sum.
- Parse
-nameflag and print greeting. - Build a
switchon day number (1-7). - Convert Celsius to Fahrenheit with proper formatting.
- Reverse a string safely for ASCII.
- Count vowels in a string.
- Find min/max in an
[]int. - Remove duplicates from a slice.
- Implement
contains([]string, string) bool. - Build a frequency map for words in a sentence.
- Sort a slice of ints ascending.
- Sort a slice of structs by one field.
- Write a function returning
(value, error)for divide. - Use
deferto time function execution. - Create a custom error type with context.
- Marshal struct to JSON with tags.
- Unmarshal JSON into struct and validate fields.
- Read env var with fallback default.
- Parse RFC3339 timestamp.
- Format duration nicely (
1h2m3s).
Files and CLI Tools (21-40)
- Read file and print line count.
- Read file and print byte count.
- Read from stdin and uppercase output.
- Build tiny
head -nclone. - Build tiny
tail -nclone. - Filter lines containing a substring.
- Replace substring in each line and print.
- Walk directory and count files.
- Walk directory and sum file sizes.
- Print top 10 largest files in a directory tree.
- Build file extension counter (
.go,.md, etc.). - Skip hidden files while walking.
- Add
-jsonoutput mode to a CLI tool. - Add
-quietand-verboselog levels. - Create a checksum (SHA-256) for one file.
- Compare two files by checksum.
- Build tiny
wc(lines/words/bytes). - Build tiny
grepwith regex input. - Add case-insensitive flag to grep clone.
- Print first match index and line number.
Structs, Methods, Interfaces (41-60)
- Define
Userstruct and constructor. - Add
String()method to struct. - Add pointer receiver mutator method.
- Add value receiver read-only method.
- Implement small interface (
Runner) with two types. - Compose two structs via embedding.
- Resolve method name conflict in embedded structs.
- Implement
io.Writerthat counts bytes. - Implement
io.Readerover in-memory string. - Build a decorator function for timing any function.
- Build
Optionpattern for server config. - Validate config and return combined error.
- Compare two structs for equality constraints.
- Parse CSV into typed struct slice.
- Convert struct slice to map by key field.
- Implement generic
Maphelper for slices. - Implement generic
Filterhelper. - Implement generic
Reducehelper. - Create custom type alias with methods.
- Add unit tests for all methods.
Errors and Reliability (61-80)
- Wrap errors with
%wacross 3 layers. - Detect sentinel error with
errors.Is. - Detect custom type with
errors.As. - Build retry helper with max attempts.
- Add exponential backoff to retry helper.
- Add jitter to retry backoff.
- Build circuit-breaker lite (open/close states).
- Add timeout via
context.WithTimeout. - Add cancellation via parent context.
- Build
musthelper for internal tooling only. - Build panic recovery middleware for HTTP.
- Capture stack trace on panic and log.
- Return structured JSON error response.
- Add error codes enum for API errors.
- Validate all CLI input and fail fast.
- Add dead-letter file for failed jobs.
- Add graceful shutdown on SIGINT.
- Add idempotency key check for commands.
- Add bounded retries for network call.
- Add fallback path when primary call fails.
Concurrency Basics (81-100)
- Launch 5 goroutines and wait with
WaitGroup. - Fan-out tasks to worker pool.
- Fan-in results from workers.
- Add context cancellation to worker pool.
- Add timeout to a blocking goroutine.
- Use buffered channel to smooth bursts.
- Use unbuffered channel to enforce handoff.
- Prevent goroutine leak on early return.
- Build bounded semaphore using channel.
- Merge two channels into one output.
- Implement producer-consumer with backpressure.
- Add
selectwith timeout case. - Add
selectwith default non-blocking case. - Protect shared map with mutex.
- Replace mutex map with
sync.Mapand compare. - Use
sync.Oncefor singleton init. - Use
sync.Condfor queue notifications. - Build rate limiter with ticker.
- Build token bucket limiter.
- Profile goroutine count during load.
Networking and HTTP (101-120)
- Build
/healthendpoint. - Add
/readyendpoint with dependency check. - Parse query params safely.
- Parse JSON request body with size limit.
- Return JSON response helper function.
- Add middleware for request logging.
- Add middleware for panic recovery.
- Add middleware for request ID.
- Add middleware for timeout context.
- Add simple in-memory rate limit middleware.
- Build URL shortener
POST /shorten. - Build URL shortener
GET /{code}redirect. - Add TTL to short links.
- Add short-link collision handling.
- Add ETag support to one endpoint.
- Add graceful server shutdown with context.
- Build HTTP client with timeout + retries.
- Build HTTP client with custom transport.
- Add gzip compression middleware.
- Benchmark one endpoint with your load tester.
Data and Persistence (121-140)
- Use
encoding/csvto read sample data. - Use
encoding/csvto write report file. - Store key-value data in BoltDB (or bbolt).
- Build repository interface over in-memory store.
- Add file-backed repository implementation.
- Add migration version field to data model.
- Add optimistic locking field (
version). - Add simple cache with TTL map.
- Add cache invalidation on write.
- Serialize map to JSON snapshot file.
- Recover state from snapshot on startup.
- Add periodic snapshot goroutine.
- Add checksum to snapshot file.
- Add snapshot restore validation.
- Build append-only event log file.
- Replay event log to rebuild state.
- Add compaction command for old events.
- Add corruption detection for events.
- Add CLI export to CSV.
- Add CLI import from CSV.
Testing Workout (141-160)
- Write table-driven tests for parser.
- Add subtests by category.
- Add golden file test for CLI output.
- Add benchmark with
b.Loop. - Add benchmark with
-benchmemanalysis. - Add fuzz test for JSON decode path.
- Add race test and fix discovered issue.
- Add test helper for temporary fixture files.
- Add
t.Cleanupin all integration tests. - Use
httptestfor handler test. - Use
httptest.Serverfor client test. - Use
testing/synctestfor flaky timer logic. - Add tests for retry backoff boundaries.
- Add tests for context timeout path.
- Add tests for panic recovery middleware.
- Add tests for rate limiter edge case.
- Add tests for short-link collision behavior.
- Add tests for file checksum mismatch path.
- Add integration test with build tag
integration. - Add CI test command matrix in README.
Linux Tooling Track (161-180)
- Extend
lsclone with-Rrecursion. - Extend
lsclone with colorized output. - Extend
catclone with-Ttab markers. - Extend
grepclone with invert match-v. - Extend
grepclone with count-only-c. - Extend
tailclone to handle file rotation. - Extend
duclone with max depth flag. - Extend
findclone with regex match mode. - Extend
wcclone with rune count flag. - Build mini
xargsclone. - Build mini
cutclone. - Build mini
sortclone. - Build mini
uniqclone. - Build mini
teeclone. - Build mini
whichclone. - Build mini
psclone using/proc(Linux). - Build mini
freeclone from/proc/meminfo. - Build mini
uptimeclone from/proc/uptime. - Build mini
dfclone usingsyscall.Statfs. - Build mini
watchclone for repeated commands.
Advanced TUI and Infra Track (181-200)
- Add CPU history sparkline to TUI monitor.
- Add memory history sparkline to TUI monitor.
- Add keybinding help modal in TUI.
- Add theme toggle (light/dark terminal palette).
- Add status bar with connection state.
- Add periodic refresh ticker with pause key.
- Add filtering by VM status in Proxmox TUI.
- Add node selector screen in Proxmox TUI.
- Add VM details pane in Proxmox TUI.
- Add confirmation dialog before VM stop.
- Add async action queue and progress states.
- Add retry-on-429 for Proxmox API calls.
- Add structured logs for every API request.
- Add audit log file for start/stop actions.
- Add SSH orchestrator output to JSON report.
- Add SSH orchestrator parallel limit per subnet.
- Add host reachability precheck before SSH.
- Add rollout mode: canary then full batch.
- Add rollback command set for failed rollout.
- Build capstone: TUI panel that triggers SSH jobs and shows live results.
Chapter References in This Book
Use these while solving workouts:
- Foundations:
/Users/king/Workspace/Repos/books/books/Go/content/01-foundations - Core:
/Users/king/Workspace/Repos/books/books/Go/content/02-core - Concurrency:
/Users/king/Workspace/Repos/books/books/Go/content/07-concurrency-parallelism - Testing:
/Users/king/Workspace/Repos/books/books/Go/content/06-testing - Projects:
/Users/king/Workspace/Repos/books/books/Go/content/99-projects
Step-by-Step Explanation
- Pick a small set of exercises by track.
- Timebox each attempt to ten minutes.
- Record one takeaway and one weakness after each exercise.
- Revisit chapter references when blocked.
- Re-solve selected problems from memory weekly.
Learning Goals
- Build consistency, not one-time intensity.
- Improve retrieval and transfer of Go patterns.
- Progress from syntax fluency to engineering fluency.