A tiny web framework
Real web frameworks map addresses like /users/ali to functions and fill templates with values. This lesson builds both ideas in a few dozen lines on top of WebServer.
What you will learn#
- routes with parameters:
/users/:name/posts/:id, - one catch-all handler (
notFound) that decides with a router, - a template with
{{name}}places and automatic escaping, - calling a function by its name (
call), - testing the whole thing in one program.
The idea#
WebServer maps a fixed address to a handler. A real site has addresses with changing parts: /users/ali, /users/sara/posts/7. Instead of one route for each user, a framework keeps a pattern (/users/:name) and, for each request, finds the pattern that fits and extracts the parameters (name = ali).
The program#
# a tiny web framework - routes with parameters (/users/:id), templates ({{name}}) and one catch-all handler
load "dotnet.ring"
using {
"System.Net"
"System.Net.Http"
"RingDotNet.Web"
}
oServer = ""
oClient = ""
oRouter = ""
func main
oServer = new WebServer("http://127.0.0.1:0")
oRouter = new Router()
oRouter.add("GET","/","homePage")
oRouter.add("GET","/users/:name","userPage")
oRouter.add("GET","/users/:name/posts/:id","postPage")
oServer.notFound("dispatch") # every request that has no ordinary route comes here: the router decides
oClient = new HttpClient()
oTimeout = new TimeSpan().FromSeconds(5)
oClient.Timeout = oTimeout
for cPath in ["/","/users/ali","/users/sara/posts/7","/users/<b>sara","/nothing/here"]
aAnswer = fetch(cPath)
? padRight(cPath,22) + aAnswer[1] + " " + aAnswer[2]
next
oServer.close()
func padRight cText, nWidth
while len(cText) < nWidth
cText += " "
end
return cText
# ---------------------------------------------------------------- the framework
# the one handler of the web server: it asks the router
func dispatch oRequest
aMatch = oRouter.find(oRequest.method(),oRequest.path())
if len(aMatch) = 0
return [404,"text/plain","no page " + oRequest.path()]
ok
cHandler = aMatch[1]
aParams = aMatch[2]
return call cHandler(oRequest,aParams)
# a template: {{name}} is replaced by the value, with HTML characters escaped
func render cTemplate, aValues
for aPair in aValues
cTemplate = substr(cTemplate,"{{" + aPair[1] + "}}",escape(aPair[2]))
next
return [200,"text/html",cTemplate]
func escape cText
cText = substr(cText,"&","&")
cText = substr(cText,"<","<")
cText = substr(cText,">",">")
return cText
# ---------------------------------------------------------------- the pages
func homePage oRequest, aParams
return render("<h1>Welcome</h1>",[])
func userPage oRequest, aParams
return render("<h1>User {{name}}</h1>",aParams)
func postPage oRequest, aParams
return render("<h1>Post {{id}} of {{name}}</h1>",aParams)
# ---------------------------------------------------------------- a test client
func fetch cPath
oTask = oClient.GetAsync(oServer.url() + cPath)
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)
return [oResponse.StatusCode,oBody.Result]
# "/users/ali" -> ["", "users", "ali"]
func splitPath cText
return str2list(substr(cText,"/",nl))
# ---------------------------------------------------------------- the router (a class goes last: functions after it would belong to it)
class Router
aRoutes = [] # [method, [parts of the pattern], handler name]
func init
return self
func add cMethod, cPattern, cHandler
aRoutes + [cMethod,splitPath(cPattern),cHandler]
# the first route that fits: returns [handler, [[parameter name, value], ...]] or an empty list
func find cMethod, cPath
aParts = splitPath(cPath)
for aRoute in aRoutes
if aRoute[1] = cMethod and len(aRoute[2]) = len(aParts)
aParams = matchParts(aRoute[2],aParts)
if islist(aParams)
return [aRoute[3],aParams]
ok
ok
next
return []
# a part that starts with : is a parameter, the other parts must be equal
func matchParts aPattern, aParts
aParams = []
for nIndex = 1 to len(aPattern)
cWanted = aPattern[nIndex]
if left(cWanted,1) = ":"
aParams + [substr(cWanted,2),aParts[nIndex]]
but cWanted != aParts[nIndex]
return false
ok
next
return aParams/ OK <h1>Welcome</h1>
/users/ali OK <h1>User ali</h1>
/users/sara/posts/7 OK <h1>Post 7 of sara</h1>
/users/<b>sara OK <h1>User <b>sara</h1>
/nothing/here NotFound no page /nothing/hereHow it works#
The router#
Router.add(method, pattern, handlerName) stores the pattern split into parts. find(method, path) splits the real path too, and compares part by part: a part that starts with : matches anything and is saved as a parameter, any other part must be equal. A path with a different number of parts can never match. The result is [handler, parameters] — or an empty list.
One handler for everything#
oServer.notFound("dispatch") registers a handler for every request that has no ordinary route. Here that is every request, so dispatch is the only entry of the application: it asks the router, answers 404 when nothing fits, and otherwise calls the page function by its name: call cHandler(oRequest,aParams).
Pages and templates#
A page function gets the request and the parameters and returns the answer of render. render("<h1>User {{name}}</h1>", aParams) replaces each {{key}} with its value — escaped: the fourth request of the output asks for the user <b>sara, and the page shows <b>sara. If the value were put into the page as it is, a visitor could write HTML or scripts into your site (the tutorial A small web site and the tutorial Login, sessions and cookies explain why this matters).
Order in a Ring file#
The class Router is at the end of the file. In Ring, functions written after a class belong to that class, so classes go last.
What you learned#
- patterns with
:parameters, - a router that finds the page and the values,
notFoundas the single entry point,- templates with escaping,
callfor a function name.
Exercises#
- Add a route
POST /users/:namefor a form, and look atoRequest.form("field"). - Support a
*part that matches the rest of the path (/files/*). - Put the templates in files in a
viewsfolder and read them withFile.ReadAllText.