CNAME / Redirect Chain Resolver (Go)
Topics: graphs, chain walk, loop detection
Problem
A name server (or an HTTP redirect follower) chases a CNAME/Location chain: each name points at
the next until one has no further record — the canonical target. Walk the chain from a start
name to that target, but refuse to chase forever.
func Resolve(cnames map[string]string, start string, maxHops int) (string, error)
type LoopError struct { Chain []string }
type TooLongError struct { MaxHops int }
cnames maps a name to the single name it redirects to. A name with no entry is the
canonical target; resolving it returns itself (zero hops).
- Each hop follows one link. Return a
*TooLongError if resolving would follow more than
maxHops links.
- Return a
*LoopError if the chain revisits a name (including a name that points to itself);
Chain is the names visited, in order, before the repeat.
{www→example.com, example.com→lb-01}; start=www, maxHops=10 → "lb-01"
{a→b, b→a}; start=a → *LoopError{Chain:[a,b]}
{a→b, b→c, c→d}; start=a, maxHops=2 → *TooLongError{MaxHops:2}
It's a single walk down a linked chain: keep a seen set to catch loops and a hop counter to cap
the length.
Run
go test -v ./challenges/cname-resolver/go/
Sign in to submit your solution.