Project 1 — URL shortener
Validation, random codes, redirects, clashes, and a Postgres store.
A user submits javascript:alert(1) to shorten. url.Parse returns no error. What should the service do?
All questions with explanations (answers shown)
1. A user submits
javascript:alert(1)to shorten.url.Parsereturns no error. What should the service do?Answer: Reject it: only allow
httporhttpsschemes, with a non-empty hosturl.Parseaccepts many strings that are not usable web links. Checking the scheme and host is what stops the shortener redirecting people to script URLs.2. Why are codes generated with
crypto/randand notmath/rand?Answer: Codes from
math/randare predictable, so someone could guess links that have not been shared yetmath/randis not designed to be unpredictable. For anything a stranger should not guess, usecrypto/rand.3. The alphabet leaves out look-alike characters such as
0,O,1,landI. Why?Answer: People read and type codes by hand, and look-alikes cause wrong links
Every character is valid in a URL path. Leaving out characters people confuse makes codes safe to read aloud or copy from paper, at the cost of a slightly smaller alphabet.
4. Two requests generate the same random code at the same moment. What actually stops both being saved?
Answer: The
UNIQUEconstraint oncode, with the duplicate-key error turned intoErrCodeTakenand the save retried with a new codeA check-then-insert has a gap between the two steps. Only the database constraint decides atomically. The service retries a few times on
ErrCodeTakenand treats any other error as a real failure.5. The redirect sends
301 Moved Permanently. Later the owner edits where the link points. What happens to people who already visited?Answer: Their browsers may keep going to the old destination, because a 301 is cached hard
Browsers cache a 301 aggressively, often with no expiry. Use 302 unless the link can never change. It also lets you count clicks, because every visit reaches your server.
6. Where is the
Storeinterface that the service uses declared?Answer: In the service package, the one that uses it, with only the methods it needs
Go interfaces are declared by the consumer. A small interface in the service package means the memory store, the Postgres store and a test fake all satisfy it without importing each other.
7. The Postgres store gets
sql.ErrNoRowswhen looking up a code. What should it return?Answer: The model's own
ErrNotFound, the same error the memory store returnsTranslate driver errors at the storage boundary. The handler then checks
errors.Is(err, model.ErrNotFound)without knowing which store is behind it.8. The create handler reads JSON with
json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20)). What doesMaxBytesReaderprotect against?Answer: A client sending a huge body to use up memory
It stops reading after the limit and returns an error, so one request cannot make the server buffer gigabytes. Slow headers are what
ReadHeaderTimeoutis for.