Skip to content

Table of Contents

Month 2 · Week 4 — Exercises

Practice for the Week 4 themes (tooling, build, and the URL-shortener project). Each folder is its own package with a solution .go file and a table-driven *_test.go. Standard library only.

Exercise Concept Day Run tests
base62/ base62 Encode/Decode + round-trip property 055 go test ./base62
urlstore/ sync.RWMutex-guarded in-memory store, de-dup, -race 055 go test -race ./urlstore
normalizeurl/ URL canonicalization with net/url (idempotent) 055 go test ./normalizeurl

How to use

  1. Try it yourself first — move the solution .go aside and re-implement from the prompt.
  2. Run go test ./... from this directory.
  3. Compare with the provided solution; log differences in your day note's "Mistakes" section.

Prompts

  • base62: implement Encode(n uint64) string (with Encode(0) == "0") and Decode(s string) (uint64, error) over the alphabet 0-9A-Za-z. Return a sentinel error (errors.Is-matchable) for any character outside the alphabet and for the empty string. Prove Decode(Encode(n)) == n.
  • urlstore: implement a Store with New, Save(long) code, Resolve(code) (long, ok), and Len. Save must be idempotent (same URL -> same code) and concurrency-safe (guard the maps with a sync.RWMutex). Verify with go test -race.
  • normalizeurl: implement Normalize(raw) (string, error) with net/url: default a missing scheme to http://, lowercase scheme + host, drop the default port (:80/:443), make an empty path /, drop the fragment, keep the query, and reject non-http(s) schemes. It must be idempotent.

Tooling drills (no test files — run these by hand)

go vet ./...                 # report suspicious constructs (Printf args, etc.)
gofmt -l .                   # list files that aren't gofmt-clean (empty = good)
go test -race ./urlstore     # data-race detector
go build ./...               # smoke-build everything
GOOS=windows GOARCH=amd64 go build ./...   # cross-compile check

Results

Exercise Tests Status
base62 TestEncode, TestDecode, TestRoundTrip
urlstore TestSaveAndResolve, TestSaveIsIdempotent, TestResolveMissing, TestConcurrentSave
normalizeurl TestNormalize, TestNormalizeErrors, TestIdempotent

Exercises