The app stores short links, but a short link is only useful if opening it takes you to the long URL. A short link is the app's address, a slash, then the code: /1, /zz.
Any text in the path: a pattern like "GET /{code}" has a wildcard: {code} matches any one part of the path, and r.PathValue("code") hands it to the handler as a string. That suits codes made of digits and letters.
Found or not: reading a map with two variables gives the value and a bool that is false when the key is missing, as in price, ok := prices["mug"]. A missing key never crashes: it gives the zero value, "" for a string.
Redirects: http.Redirect(w, r, url, 302) answers with the status 302 Found and a Location header set to the URL. A browser that gets it opens that URL right away. For example, on another route:
app.HandleFunc("GET /docs", func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "https://go.dev/doc/", 302)
})
After two POST /links made the codes 1 and 2, your app must answer:
GET /1 → 302 Location: https://www.python.org/downloads/
GET /2 → 302 Location: https://en.wikipedia.org/wiki/URL_shortening
GET /3 → 404 {"error": "Link not found"}
GET /zz → 404 {"error": "Link not found"}
And once a third POST /links made the code 3:
GET /3 → 302 Location: https://flask.palletsprojects.com/en/stable/quickstart/
Your task: inside newApp, below the /links handler, add GET /{code}. When the code isn't in links, answer 404 with {"error": "Link not found"} using writeJSON; otherwise redirect with 302 to the stored URL.
Assignment
Follow the Coding Tutorial to add the GET /{code} handler that sends a short link on to its long URL.
Hint
Check for a missing code first. Writing an answer doesn't end a Go handler, so put return right after the 404, or the handler goes on to the redirect.
Free plan: 30 tutor messages. PRO is unlimited.
