A project: a link shortener
A link shortener turns a long address into a short code and sends visitors to the long address. This project is a web service that makes codes from a counter, answers with a 302 redirect and a Location header, counts the visits, and refuses addresses that are not http or https.
What you will learn#
- a web service with
POST /shorten,GET /statsand a catch-all handler (notFound), - base 62 codes made from a counter,
- the redirect: status
302 Foundand the headerLocation, - a client that does not follow redirects, so a test can see them,
- answering 400 and 404,
- why a redirecting service must check where it redirects.
The tutorial A web service with a database and the tutorial Route templates made services and routes. This project is a small complete one.
The program#
# a project: a link shortener - a web service that makes short codes, redirects with 302, counts the visits and refuses bad addresses
load "dotnet.ring"
using {
"System"
"System.Net.Http"
"System.Text"
"RingDotNet.Web"
}
oServer = ""
oClient = ""
cUrl = ""
aLinks = [] # [code, address, visits]
nCounter = 1000 # the next number to turn into a code
func main
oServer = new WebServer("http://127.0.0.1:0")
oServer.onPost("/shorten","shorten")
oServer.onGet("/stats","statsOverview")
oServer.notFound("visit") # any other address is a short code
cUrl = oServer.url()
# The client does NOT follow redirects, so that the test can see the answer 302 and its Location header
oHandler = new HttpClientHandler()
oHandler.AllowAutoRedirect = False
oClient = (new HttpClient).@New(oHandler)
# 1. A code is a number written in base 62 (0-9, a-z, A-Z): short and made of safe characters. The numbers start at 1000 so that the
# codes have at least two characters.
? "1. numbers as codes: 1000 -> " + toCode(1000) + ", 1001 -> " + toCode(1001) + ", 3844 -> " + toCode(3844) + ", 238328 -> " + toCode(238328)
# 2. Make short links
? nl + "2. POST /shorten"
for cAddress in [ "https://example.com/a/very/long/address?with=parameters&and=more", "https://example.org/", "https://example.com/a/very/long/address?with=parameters&and=more" ]
aResult = post("/shorten","address=" + (new Uri).EscapeDataString(cAddress))
? " " + aResult[1] + " " + aResult[2]
next
# 3. Visit a short link: the answer is a redirect, and the header Location has the address
? nl + "3. GET /" + toCode(1000) + " (a redirect: the client does not follow it)"
aResult = fetch("/" + toCode(1000))
? " " + aResult[1] + ", Location: " + aResult[3]
# 4. Visits are counted
fetch("/" + toCode(1000))
fetch("/" + toCode(1001))
? nl + "4. GET /stats"
aResult = fetch("/stats")
? " " + aResult[2]
# 5. Errors: an unknown code is 404, a missing or bad address is 400, and the wrong method is not found
? nl + "5. errors:"
? " GET /zzzz -> " + fetch("/zzzz")[1]
? " POST /shorten, no address -> " + post("/shorten","")[1]
? " POST /shorten, not a URL -> " + post("/shorten","address=hello+world")[1]
? " POST /shorten, a script -> " + post("/shorten","address=" + (new Uri).EscapeDataString("javascript:alert(1)"))[1]
oServer.close()
# ---------------------------------------------------------------- the service
# the code of a number: its digits in base 62
func toCode nNumber
cDigits = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
cCode = ""
n = nNumber
while n > 0
cCode = substr(cDigits,n % 62 + 1,1) + cCode
n = floor(n / 62)
end
return cCode
# Only http and https addresses are accepted. An address like "javascript:..." in a redirect would run a script in the browser of
# the visitor: a shortener must check what it redirects to.
func isAllowed cAddress
oAbsolute = (new Uri).TryCreate(cAddress,"Absolute")
if not oAbsolute[1]
return False
ok
cScheme = oAbsolute[2].Scheme
return cScheme = "http" or cScheme = "https"
func shorten oRequest
cAddress = trim(oRequest.form("address"))
if cAddress = ""
return [400,"text/plain","the field address is needed"]
but not isAllowed(cAddress)
return [400,"text/plain","the address must be a http or https address"]
ok
# the same address gets the same code
for aLink in aLinks
if aLink[2] = cAddress
return [200,"text/plain",aLink[1] + " (already known)"]
ok
next
cCode = toCode(nCounter)
nCounter++
aLinks + [ cCode, cAddress, 0 ]
return [201,"text/plain",cCode + " " + shortAddress(cAddress)]
func shortAddress cAddress
if len(cAddress) <= 28
return cAddress
ok
return left(cAddress,25) + "..."
# any other path: its text after the first / is the code
func visit oRequest
cCode = substr(oRequest.path(),2)
for i = 1 to len(aLinks)
if aLinks[i][1] = cCode
aLinks[i][3] = aLinks[i][3] + 1
oRequest.setHeader("Location",aLinks[i][2])
return [302,"text/plain",""]
ok
next
return [404,"text/plain","no such code"]
func statsOverview oRequest
cText = ""
for aLink in aLinks
if cText != ""
cText += "; "
ok
cText += aLink[1] + ": " + aLink[3] + " visits"
next
return cText
# ---------------------------------------------------------------- the client for the test
# one request is sent, the server answers it (serveOne), and the answer comes back as [status, text, location]
func fetch cPath
return exchange(oClient.GetAsync(cUrl + cPath))
func post cPath,cForm
return exchange(oClient.PostAsync([ :requestUri = cUrl + cPath, :content = (new StringContent).@New([ :content = cForm, :encoding = new UTF8Encoding(), :mediaType = "application/x-www-form-urlencoded" ]) ]))
func exchange oTask
for nTry = 1 to 50
if oServer.serveOne(100)
exit
ok
next
oTask.Wait(NULL)
oResponse = oTask.Result
oBody = oResponse.Content.ReadAsStringAsync(NULL)
oBody.Wait(NULL)
cLocation = ""
aFound = oResponse.Headers.TryGetValues("Location")
if aFound[1]
cLocation = aFound[2].toList()[1]
ok
return [ "" + oResponse.StatusCode, oBody.Result, cLocation ]1. numbers as codes: 1000 -> g8, 1001 -> g9, 3844 -> 100, 238328 -> 1000
2. POST /shorten
Created g8 https://example.com/a/ver...
Created g9 https://example.org/
OK g8 (already known)
3. GET /g8 (a redirect: the client does not follow it)
Found, Location: https://example.com/a/very/long/address?with=parameters&and=more
4. GET /stats
g8: 2 visits; g9: 1 visits
5. errors:
GET /zzzz -> NotFound
POST /shorten, no address -> BadRequest
POST /shorten, not a URL -> BadRequest
POST /shorten, a script -> BadRequestThis program uses a few generic functions (dnNew, dnStatic) where a class cannot be used. The lesson The generic functions explains them.
How it works#
The routes#
onPost("/shorten", "shorten") makes a short link, onGet("/stats", "statsOverview") lists the visits, and notFound("visit") handles every other path: the text after the first / is a code. The handler of an unknown path is the way to make a service whose addresses are data, not a fixed list. (The status names in the output, Created, Found, NotFound and BadRequest, are the names of the status codes 201, 302, 404 and 400.)
Codes#
toCode writes a number in base 62 with the digits 0-9, a-z and A-Z: 62 symbols that are safe in a URL and short. The counter starts at 1000, so the codes have at least two characters, and three characters are enough for 238,000 links. A code from a counter is predictable: anybody can guess the next one. For links that must be private use random codes (the tutorial Randomness) and check that the code is not used.
One address, one code#
shorten first looks for the address in the list: the same address gets the same code and the answer 200 (already known), and a new one gets 201 Created. The list is [code, address, visits] in memory; a real service stores it in a database (the tutorial Entity objects and migrations).
The redirect#
A redirect is an answer, not a page: the status 302 Found and the header Location with the new address. The handler calls oRequest.setHeader("Location", address) and returns [302, "text/plain", ""]. A browser then goes to the address by itself. The client of the test is made with AllowAutoRedirect = False; the default client would follow the redirect and fetch the long address, which is not what the test wants to see. visit also counts the visit.
Errors#
An unknown code is 404. A missing field or an address that is not valid is 400 Bad Request. The function isAllowed uses Uri.TryCreate(text, "Absolute"), which answers [success, uri], and accepts only the schemes http and https.
Why check the address#
A shortener that redirects to any text is dangerous. javascript:alert(1) is an address too, and a link or a redirect to it can run a script in some contexts. Another problem is a short, innocent-looking code that leads to a harmful site. A real service checks the scheme (as here), and often the destination too, and it never redirects to an address that a request takes from the address bar of another visitor without checking it (an open redirect).
The service runs on the Ring thread, and the test calls serveOne between sending a request and reading the answer. A real service calls run() and serves until it is stopped.
What you learned#
- a service with a catch-all handler,
- base 62 codes,
- the 302 redirect and the
Locationheader, - testing redirects with a client that does not follow them,
- checking the address before redirecting.
Exercises#
- Add
GET /stats/CODEthat shows the visits of one link as JSON (webJson). - Let the caller choose the code (
code=docs), and refuse a code that is already used. - Add the time of the last visit and show it in the statistics.
- Make the codes random and check that a code was not used before.