forked from dom96/jester
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jester.nim
831 lines (709 loc) · 29.3 KB
/
jester.nim
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
# Copyright (C) 2015 Dominik Picheta
# MIT License - Look at license.txt for details.
import asynchttpserver, net, strtabs, re, tables, parseutils, os, strutils, uri,
scgi, cookies, times, mimetypes, asyncnet, asyncdispatch, macros, md5,
logging, httpcore, asyncfile
import jester/private/[patterns, errorpages, utils]
from cgi import decodeData, decodeUrl, CgiError
export strtabs
export tables
export httpcore
export NodeType # TODO: Couldn't bindsym this.
export MultiData
export HttpMethod
type
Jester = object
httpServer*: AsyncHttpServer
settings: Settings
matchProc: proc (request: Request, response: Response): Future[bool] {.gcsafe, closure.}
Settings* = ref object
staticDir*: string # By default ./public
appName*: string
mimes*: MimeDb
port*: Port
bindAddr*: string
reusePort*: bool
errorFilter*: proc(e: ref Exception, res: var Response) {.closure, gcsafe.}
MatchType* = enum
MRegex, MSpecial
Request* = ref object
params*: StringTableRef ## Parameters from the pattern, but also the
## query string.
matches*: array[MaxSubpatterns, string] ## Matches if this is a regex
## pattern.
body*: string ## Body of the request, only for POST.
## You're probably looking for ``formData``
## instead.
headers*: HttpHeaders ## Headers received with the request.
## Retrieving these is case insensitive.
formData*: MultiData ## Form data; only present for
## multipart/form-data
port*: int
host*: string
appName*: string ## This is set by the user in ``run``, it is
## overriden by the "SCRIPT_NAME" scgi
## parameter.
pathInfo*: string ## This is ``.path`` without ``.appName``.
secure*: bool
path*: string ## Path of request.
cookies*: StringTableRef ## Cookies from the browser.
ip*: string ## IP address of the requesting client.
reqMeth*: HttpMethod ## Request method, eg. HttpGet, HttpPost
settings*: Settings
Response* = ref object
client*: AsyncSocket ## For raw mode.
data*: tuple[action: CallbackAction, code: HttpCode,
headers: StringTableRef, content: string]
CallbackAction* = enum
TCActionSend, TCActionRaw, TCActionPass, TCActionNothing
Callback = proc (request: jester.Request, response: Response): Future[void] {.gcsafe, closure.}
{.deprecated: [TJester: Jester, PSettings: Settings, TMatchType: MatchType,
TMultiData: MultiData, PRequest: Request, PResponse: Response,
TReqMeth: HttpMethod, ReqMeth: HttpMethod, TCallbackAction: CallbackAction,
TCallback: Callback].}
const jesterVer = "0.1.0"
proc createHeaders(status: string, headers: StringTableRef): string =
result = ""
if headers != nil:
for key, value in headers:
result.add(key & ": " & value & "\c\L")
result = "HTTP/1.1 " & status & "\c\L" & result & "\c\L"
proc statusContent(c: AsyncSocket, status, content: string,
headers: StringTableRef) {.async.} =
var newHeaders = headers
newHeaders["Content-Length"] = $content.len
let headerData = createHeaders(status, headers)
try:
await c.send(headerData & content)
logging.debug(" $1 $2" % [$status, $headers])
except:
logging.error("Could not send response: $1" % osErrorMsg(osLastError()))
proc sendHeaders*(response: Response, status: HttpCode,
headers: StringTableRef) {.async.} =
## Sends ``status`` and ``headers`` to the client socket immediately.
## The user is then able to send the content immediately to the client on
## the fly through the use of ``response.client``.
response.data.action = TCActionRaw
let headerData = createHeaders($status, headers)
try:
await response.client.send(headerData)
logging.debug(" $1 $2" % [$status, $headers])
except:
logging.error("Could not send response: $1" % [osErrorMsg(osLastError())])
proc sendHeaders*(response: Response, status: HttpCode): Future[void] =
## Sends ``status`` and ``Content-Type: text/html`` as the headers to the
## client socket immediately.
response.sendHeaders(status, {"Content-Type": "text/html;charset=utf-8"}.newStringTable())
proc sendHeaders*(response: Response): Future[void] =
## Sends ``Http200`` and ``Content-Type: text/html`` as the headers to the
## client socket immediately.
response.sendHeaders(Http200)
proc send*(response: Response, content: string) {.async.} =
## Sends ``content`` immediately to the client socket.
response.data.action = TCActionRaw
await response.client.send(content)
proc send*(response: Response, status: HttpCode, headers: StringTableRef,
content: string): Future[void] =
## Sends out a HTTP response comprising of the ``status``, ``headers`` and
## ``content`` specified. This is done immediately for greatest performance.
response.data.action = TCActionRaw
result = response.client.statusContent($status, content, headers)
proc stripAppName(path, appName: string): string =
result = path
if appname.len > 0:
var slashAppName = appName
if slashAppName[0] != '/' and path[0] == '/':
slashAppName = '/' & slashAppName
if path.startsWith(slashAppName):
if slashAppName.len() == path.len:
return "/"
else:
return path[slashAppName.len .. path.len-1]
else:
raise newException(ValueError,
"Expected script name at beginning of path. Got path: " &
path & " script name: " & slashAppName)
proc createReq(jes: Jester, path, body, ip: string, reqMeth: HttpMethod,
headers: HttpHeaders, params: StringTableRef): Request =
new(result)
result.params = params
result.body = body
result.appName = jes.settings.appName
result.headers = headers
if result.headers.getOrDefault("Content-Type").startswith("application/x-www-form-urlencoded"):
try:
parseUrlQuery(body, result.params)
except:
logging.warn("Could not parse URL query.")
elif (let ct = result.headers.getOrDefault("Content-Type"); ct.startsWith("multipart/form-data")):
result.formData = parseMPFD(ct, body)
result.ip = ip
if result.headers.hasKey("REMOTE_ADDR"):
result.ip = result.headers["REMOTE_ADDR"]
if result.headers.hasKey("x-forwarded-for"):
result.ip = result.headers["x-forwarded-for"]
result.host = result.headers.getOrDefault("HOST")
result.pathInfo = path.stripAppName(result.appName)
result.path = path
result.secure = false
if result.headers.hasKey("x-forwarded-proto"):
let proto = result.headers["x-forwarded-proto"]
case proto.toLowerAscii()
of "https":
result.secure = true
of "http":
result.secure = false
else:
logging.warn("Unknown x-forwarded-proto ", proto)
if (let p = result.headers.getOrDefault("SERVER_PORT"); p != ""):
result.port = p.parseInt
else:
result.port = if result.secure: 443 else: 80
if (let cookie = result.headers.getOrDefault("Cookie"); cookie != ""):
result.cookies = parseCookies(cookie)
else: result.cookies = newStringTable()
result.reqMeth = reqMeth
result.settings = jes.settings
# TODO: Cannot capture 'paths: varargs[string]' here.
proc sendStaticIfExists(resp: Response, req: Request, jes: Jester,
paths: seq[string]) {.async.} =
for p in paths:
if existsFile(p):
var fp = getFilePermissions(p)
if not fp.contains(fpOthersRead):
await resp.client.statusContent($Http403, error($Http403, jesterVer),
{"Content-Type": "text/html;charset=utf-8"}.newStringTable)
return
let fileSize = getFileSize(p)
let mimetype = jes.settings.mimes.getMimetype(p.splitFile.ext[1 .. ^1])
if fileSize < 10_000_000: # 10 mb
var file = readFile(p)
var hashed = getMD5(file)
# If the user has a cached version of this file and it matches our
# version, let them use it
if req.headers.hasKey("If-None-Match") and req.headers["If-None-Match"] == hashed:
await resp.client.statusContent($Http304, "", newStringTable())
else:
await resp.client.statusContent($Http200, file, {
"Content-Type": mimetype,
"ETag": hashed }.newStringTable)
else:
let headers = {
"Content-Type": mimetype,
"Content-Length": $fileSize
}.newStringTable
await resp.sendHeaders(Http200, headers)
var fileStream = newFutureStream[string]("sendStaticIfExists")
var file = openAsync(p, fmRead)
# Let `readToStream` write file data into fileStream in the
# background.
asyncCheck file.readToStream(fileStream)
# The `writeFromStream` proc will complete once all the data in the
# `bodyStream` has been written to the file.
while true:
let (hasValue, value) = await fileStream.read()
if hasValue:
await resp.client.send(value)
else:
break
file.close()
return
# If we get to here then no match could be found.
await resp.client.statusContent($Http404, error($Http404, jesterVer),
{"Content-Type": "text/html;charset=utf-8"}.newStringTable)
proc defaultErrorFilter(e: ref Exception, res: var Response) =
let traceback = getStackTrace(e)
var errorMsg = e.msg
if errorMsg.isNil: errorMsg = "(nil)"
let error = traceback & errorMsg
logging.error(error)
res.data.headers = {"Content-Type": "text/html;charset=utf-8"}.newStringTable
res.data.content = routeException(error.replace("\n", "<br/>\n"), jesterVer)
res.data.code = Http502
proc handleRequest(jes: Jester, client: AsyncSocket,
path, query, body, ip: string, reqMethod: HttpMethod,
headers: HttpHeaders) {.async.} =
var params = {:}.newStringTable()
try:
for key, val in cgi.decodeData(query):
params[key] = val
except CgiError:
logging.warn("Incorrect query. Got: $1" % [query])
var matched = false
var req: Request
try:
req = createReq(jes, path, body, ip, reqMethod, headers, params)
except ValueError:
client.close()
return
var resp = Response(client: client)
logging.debug("$1 $2" % [$reqMethod, req.pathInfo])
var failed = false # Workaround for no 'await' in 'except' body
var matchProcFut: Future[bool]
try:
matchProcFut = jes.matchProc(req, resp)
matched = await matchProcFut
except:
# Handle any errors by showing them in the browser.
# TODO: Improve the look of this.
failed = true
if failed:
if jes.settings.errorFilter.isNil:
defaultErrorFilter(matchProcFut.error, resp)
else:
jes.settings.errorFilter(matchProcFut.error, resp)
await client.statusContent($resp.data.code, resp.data.content,
resp.data.headers)
return
if matched:
if resp.data.action == TCActionSend:
await client.statusContent($resp.data.code, resp.data.content,
resp.data.headers)
else:
logging.debug(" $1" % [$resp.data.action])
else:
# Find static file.
# TODO: Caching.
let publicRequested = jes.settings.staticDir / cgi.decodeUrl(req.pathInfo)
if existsDir(publicRequested):
await resp.sendStaticIfExists(req, jes,
@[publicRequested / "index.html",
publicRequested / "index.htm"])
else:
await resp.sendStaticIfExists(req, jes, @[publicRequested])
# Cannot close the client socket. AsyncHttpServer may be keeping it alive.
proc handleHTTPRequest(jes: Jester, req: asynchttpserver.Request): Future[void] =
result = handleRequest(jes, req.client, req.url.path, req.url.query,
req.body, req.hostname, req.reqMethod, req.headers)
proc newSettings*(port = Port(5000), staticDir = getCurrentDir() / "public",
appName = "", bindAddr = "", reusePort = false): Settings =
result = Settings(staticDir: staticDir,
appName: appName,
port: port,
bindAddr: bindAddr,
reusePort: reusePort)
proc serve*(
match:
proc (request: Request, response: Response): Future[bool] {.gcsafe, closure.},
settings: Settings = newSettings()) =
## Creates a new async http server or scgi server instance and registers
## it with the dispatcher.
var jes: Jester
jes.settings = settings
jes.settings.mimes = newMimetypes()
jes.matchProc = match
jes.httpServer = newAsyncHttpServer(reusePort=jes.settings.reusePort)
# Ensure we have at least one logger enabled, defaulting to console.
if logging.getHandlers().len == 0:
addHandler(logging.newConsoleLogger())
setLogFilter(when defined(release): lvlInfo else: lvlDebug)
asyncCheck jes.httpServer.serve(jes.settings.port,
proc (req: asynchttpserver.Request): Future[void] {.gcsafe, closure.} =
handleHTTPRequest(jes, req), settings.bindAddr)
if settings.bindAddr.len > 0:
logging.info("Jester is making jokes at http://$1:$2$3" %
[settings.bindAddr, $jes.settings.port, jes.settings.appName])
else:
logging.info("Jester is making jokes at http://localhost:$1$2" %
[$jes.settings.port, jes.settings.appName])
template resp*(code: HttpCode,
headers: openarray[tuple[key, value: string]],
content: string): typed =
## Sets ``(code, headers, content)`` as the response.
bind TCActionSend, newStringTable
response.data = (TCActionSend, code, headers.newStringTable, content)
break route
template resp*(content: string, contentType = "text/html;charset=utf-8"): typed =
## Sets ``content`` as the response; ``Http200`` as the status code
## and ``contentType`` as the Content-Type.
bind TCActionSend, newStringTable, strtabs.`[]=`
response.data[0] = TCActionSend
response.data[1] = Http200
response.data[2]["Content-Type"] = contentType
response.data[3] = content
break route
template resp*(code: HttpCode, content: string,
contentType = "text/html;charset=utf-8"): typed =
## Sets ``content`` as the response; ``code`` as the status code
## and ``contentType`` as the Content-Type.
bind TCActionSend, newStringTable
response.data[0] = TCActionSend
response.data[1] = code
response.data[2]["Content-Type"] = contentType
response.data[3] = content
break route
template body*(): untyped =
## Gets the body of the request.
##
## **Note:** It's usually a better idea to use the ``resp`` templates.
response.data[3]
# Unfortunately I cannot explicitly set meta data like I can in `body=` :\
# This means that it is up to guessAction to infer this if the user adds
# something to the body for example.
template headers*(): untyped =
## Gets the headers of the request.
##
## **Note:** It's usually a better idea to use the ``resp`` templates.
response.data[2]
template status*(): untyped =
## Gets the status of the request.
##
## **Note:** It's usually a better idea to use the ``resp`` templates.
response.data[1]
template redirect*(url: string): typed =
## Redirects to ``url``. Returns from this request handler immediately.
## Any set response headers are preserved for this request.
bind TCActionSend, newStringTable
response.data[0] = TCActionSend
response.data[1] = Http303
response.data[2]["Location"] = url
response.data[3] = ""
break route
template pass*(): typed =
## Skips this request handler.
##
## If you want to stop this request from going further use ``halt``.
response.data.action = TCActionPass
break outerRoute
template cond*(condition: bool): typed =
## If ``condition`` is ``False`` then ``pass`` will be called,
## i.e. this request handler will be skipped.
if not condition: break outerRoute
template halt*(code: HttpCode,
headers: varargs[tuple[key, val: string]],
content: string): typed =
## Immediately replies with the specified request. This means any further
## code will not be executed after calling this template in the current
## route.
bind TCActionSend, newStringTable
response.data = (TCActionSend, code, headers.newStringTable, content)
break route
template halt*(): typed =
## Halts the execution of this request immediately. Returns a 404.
## All previously set values are **discarded**.
halt(Http404, {"Content-Type": "text/html;charset=utf-8"}, error($Http404, jesterVer))
template halt*(code: HttpCode): typed =
halt(code, {"Content-Type": "text/html;charset=utf-8"}, error($code, jesterVer))
template halt*(content: string): typed =
halt(Http404, {"Content-Type": "text/html;charset=utf-8"}, content)
template halt*(code: HttpCode, content: string): typed =
halt(code, {"Content-Type": "text/html;charset=utf-8"}, content)
template attachment*(filename = ""): typed =
## Creates an attachment out of ``filename``. Once the route exits,
## ``filename`` will be sent to the person making the request and web browsers
## will be hinted to open their Save As dialog box.
response.data[2]["Content-Disposition"] = "attachment"
if filename != "":
var param = "; filename=\"" & extractFilename(filename) & "\""
response.data[2].mget("Content-Disposition").add(param)
let ext = splitFile(filename).ext
if not response.data[2].hasKey("Content-Type") and ext != "":
response.data[2]["Content-Type"] = getMimetype(request.settings.mimes, ext)
template `@`*(s: string): untyped =
## Retrieves the parameter ``s`` from ``request.params``. ``""`` will be
## returned if parameter doesn't exist.
if request.params.hasKey(s):
request.params[s]
else:
""
proc setStaticDir*(request: Request, dir: string) =
## Sets the directory in which Jester will look for static files. It is
## ``./public`` by default.
##
## The files will be served like so:
##
## ./public/css/style.css ``->`` http://example.com/css/style.css
##
## (``./public`` is not included in the final URL)
request.settings.staticDir = dir
proc getStaticDir*(request: Request): string =
## Gets the directory in which Jester will look for static files.
##
## ``./public`` by default.
return request.settings.staticDir
proc makeUri*(request: jester.Request, address = "", absolute = true,
addScriptName = true): string =
## Creates a URI based on the current request. If ``absolute`` is true it will
## add the scheme (Usually 'http://'), `request.host` and `request.port`.
## If ``addScriptName`` is true `request.appName` will be prepended before
## ``address``.
# Check if address already starts with scheme://
var uri = parseUri(address)
if uri.scheme != "": return address
uri.path = "/"
uri.query = ""
uri.anchor = ""
if absolute:
uri.hostname = request.host
uri.scheme = (if request.secure: "https" else: "http")
if request.port != (if request.secure: 443 else: 80):
uri.port = $request.port
if addScriptName: uri = uri / request.appName
if address != "":
uri = uri / address
else:
uri = uri / request.pathInfo
return $uri
template uri*(address = "", absolute = true, addScriptName = true): untyped =
## Convenience template which can be used in a route.
request.makeUri(address, absolute, addScriptName)
proc daysForward*(days: int): TimeInfo =
## Returns a TimeInfo object referring to the current time plus ``days``.
return getTime().getGMTime + initInterval(days = days)
template setCookie*(name, value: string, expires: TimeInfo): typed =
## Creates a cookie which stores ``value`` under ``name``.
bind setCookie
if response.data[2].hasKey("Set-Cookie"):
# A wee bit of a hack here. Multiple Set-Cookie headers are allowed.
response.data[2].mget("Set-Cookie").add("\c\L" &
setCookie(name, value, expires, noName = false))
else:
response.data[2]["Set-Cookie"] = setCookie(name, value, expires, noName = true)
proc normalizeUri*(uri: string): string =
## Remove any trailing ``/``.
if uri[uri.len-1] == '/': result = uri[0 .. uri.len-2]
else: result = uri
# -- Macro
proc copyParams(request: Request, params: StringTableRef) =
for key, val in params:
request.params[key] = val
proc guessAction(resp: Response) =
if resp.data.action == TCActionNothing:
if resp.data.content != "":
resp.data.action = TCActionSend
resp.data.code = Http200
if not resp.data.headers.hasKey("Content-Type"):
resp.data.headers["Content-Type"] = "text/html;charset=utf-8"
else:
resp.data.action = TCActionSend
resp.data.code = Http502
resp.data.headers = {"Content-Type": "text/html;charset=utf-8"}.newStringTable
resp.data.content = error($Http502, jesterVer)
proc checkAction(response: Response): bool =
guessAction(response)
case response.data.action
of TCActionSend, TCActionRaw:
result = true
of TCActionPass:
result = false
of TCActionNothing:
assert(false)
proc skipDo(node: NimNode): NimNode {.compiletime.} =
if node.kind == nnkDo:
result = node[6]
else:
result = node
proc ctParsePattern(pattern: string): NimNode {.compiletime.} =
result = newNimNode(nnkPrefix)
result.add newIdentNode("@")
result.add newNimNode(nnkBracket)
proc addPattNode(res: var NimNode, typ, text,
optional: NimNode) {.compiletime.} =
var objConstr = newNimNode(nnkObjConstr)
objConstr.add bindSym("Node")
objConstr.add newNimNode(nnkExprColonExpr).add(
newIdentNode("typ"), typ)
objConstr.add newNimNode(nnkExprColonExpr).add(
newIdentNode("text"), text)
objConstr.add newNimNode(nnkExprColonExpr).add(
newIdentNode("optional"), optional)
res[1].add objConstr
var patt = parsePattern(pattern)
for node in patt:
# TODO: Can't bindSym the node type. issue #1319
result.addPattNode(
case node.typ
of NodeText: newIdentNode("NodeText")
of NodeField: newIdentNode("NodeField"),
newStrLitNode(node.text),
newIdentNode(if node.optional: "true" else: "false"))
template setDefaultResp(): typed =
# TODO: bindSym this in the 'routes' macro and put it in each route
bind TCActionNothing, newStringTable
response.data.action = TCActionNothing
response.data.code = Http200
response.data.headers = {:}.newStringTable
response.data.content = ""
template declareSettings(): typed {.dirty.} =
when not declaredInScope(settings):
var settings = newSettings()
proc createJesterPattern(body,
patternMatchSym: NimNode, i: int): NimNode {.compileTime.} =
var ctPattern = ctParsePattern(body[i][1].strVal)
# -> let <patternMatchSym> = <ctPattern>.match(request.path)
return newLetStmt(patternMatchSym,
newCall(bindSym"match", ctPattern, parseExpr("request.pathInfo")))
proc createRegexPattern(body, reMatchesSym,
patternMatchSym: NimNode, i: int): NimNode {.compileTime.} =
# -> let <patternMatchSym> = <ctPattern>.match(request.path)
return newLetStmt(patternMatchSym,
newCall(bindSym"find", parseExpr("request.pathInfo"), body[i][1],
reMatchesSym))
proc determinePatternType(pattern: NimNode): MatchType {.compileTime.} =
case pattern.kind
of nnkStrLit:
return MSpecial
of nnkCallStrLit:
expectKind(pattern[0], nnkIdent)
case ($pattern[0].ident).normalize
of "re": return MRegex
else:
macros.error("Invalid pattern type: " & $pattern[0].ident)
else:
macros.error("Unexpected node kind: " & $pattern.kind)
proc createRoute(body, dest: NimNode, i: int) {.compileTime.} =
## Creates code which checks whether the current request path
## matches a route.
var patternMatchSym = genSym(nskLet, "patternMatchRet")
# Only used for Regex patterns.
var reMatchesSym = genSym(nskVar, "reMatches")
var reMatches = parseExpr("var reMatches: array[20, string]")
reMatches[0][0] = reMatchesSym
reMatches[0][1][1] = bindSym("MaxSubpatterns")
let patternType = determinePatternType(body[i][1])
case patternType
of MSpecial:
dest.add createJesterPattern(body, patternMatchSym, i)
of MRegex:
dest.add reMatches
dest.add createRegexPattern(body, reMatchesSym, patternMatchSym, i)
var ifStmtBody = newStmtList()
case patternType
of MSpecial:
# -> copyParams(request, ret.params)
ifStmtBody.add newCall(bindSym"copyParams", newIdentNode"request",
newDotExpr(patternMatchSym, newIdentNode"params"))
of MRegex:
# -> request.matches = <reMatchesSym>
ifStmtBody.add newAssignment(
newDotExpr(newIdentNode"request", newIdentNode"matches"),
reMatchesSym)
ifStmtBody.add body[i][2].skipDo()
var checkActionIf = parseExpr("if checkAction(response): return true")
checkActionIf[0][0][0] = bindSym"checkAction"
#ifStmtBody.add checkActionIf
# -> block route: <ifStmtBody>; <checkActionIf>
var innerBlockStmt = newStmtList(
newNimNode(nnkBlockStmt).add(newIdentNode(!"route"), ifStmtBody),
checkActionIf
)
let ifCond =
case patternType
of MSpecial:
newDotExpr(patternMatchSym, newIdentNode("matched"))
of MRegex:
infix(patternMatchSym, "!=", newIntLitNode(-1))
# -> if <patternMatchSym>.matched: <innerBlockStmt>
var ifStmt = newIfStmt((ifCond, innerBlockStmt))
# -> block <thisRouteSym>: <ifStmt>
var blockStmt = newNimNode(nnkBlockStmt).add(
newIdentNode(!"outerRoute"), ifStmt)
dest.add blockStmt
macro routes*(body: untyped): typed =
#echo(treeRepr(body))
result = newStmtList()
# -> declareSettings()
result.add newCall(bindSym"declareSettings")
var outsideStmts = newStmtList()
var matchBody = newNimNode(nnkStmtList)
matchBody.add newCall(bindSym"setDefaultResp")
var caseStmt = newNimNode(nnkCaseStmt)
caseStmt.add parseExpr("request.reqMeth")
var caseStmtGetBody = newNimNode(nnkStmtList)
var caseStmtPostBody = newNimNode(nnkStmtList)
var caseStmtPutBody = newNimNode(nnkStmtList)
var caseStmtDeleteBody = newNimNode(nnkStmtList)
var caseStmtHeadBody = newNimNode(nnkStmtList)
var caseStmtOptionsBody = newNimNode(nnkStmtList)
var caseStmtTraceBody = newNimNode(nnkStmtList)
var caseStmtConnectBody = newNimNode(nnkStmtList)
var caseStmtPatchBody = newNimNode(nnkStmtList)
for i in 0 .. <body.len:
case body[i].kind
of nnkCommand:
let cmdName = body[i][0].ident.`$`.normalize
case cmdName
of "get", "post", "put", "delete", "head", "options", "trace", "connect",
"patch":
case cmdName
of "get":
createRoute(body, caseStmtGetBody, i)
of "post":
createRoute(body, caseStmtPostBody, i)
of "put":
createRoute(body, caseStmtPutBody, i)
of "delete":
createRoute(body, caseStmtDeleteBody, i)
of "head":
createRoute(body, caseStmtHeadBody, i)
of "options":
createRoute(body, caseStmtOptionsBody, i)
of "trace":
createRoute(body, caseStmtTraceBody, i)
of "connect":
createRoute(body, caseStmtConnectBody, i)
of "patch":
createRoute(body, caseStmtPatchBody, i)
else:
discard
else:
discard
of nnkCommentStmt:
discard
else:
outsideStmts.add(body[i])
var ofBranchGet = newNimNode(nnkOfBranch)
ofBranchGet.add newIdentNode("HttpGet")
ofBranchGet.add caseStmtGetBody
caseStmt.add ofBranchGet
var ofBranchPost = newNimNode(nnkOfBranch)
ofBranchPost.add newIdentNode("HttpPost")
ofBranchPost.add caseStmtPostBody
caseStmt.add ofBranchPost
var ofBranchPut = newNimNode(nnkOfBranch)
ofBranchPut.add newIdentNode("HttpPut")
ofBranchPut.add caseStmtPutBody
caseStmt.add ofBranchPut
var ofBranchDelete = newNimNode(nnkOfBranch)
ofBranchDelete.add newIdentNode("HttpDelete")
ofBranchDelete.add caseStmtDeleteBody
caseStmt.add ofBranchDelete
var ofBranchHead = newNimNode(nnkOfBranch)
ofBranchHead.add newIdentNode("HttpHead")
ofBranchHead.add caseStmtHeadBody
caseStmt.add ofBranchHead
var ofBranchOptions = newNimNode(nnkOfBranch)
ofBranchOptions.add newIdentNode("HttpOptions")
ofBranchOptions.add caseStmtOptionsBody
caseStmt.add ofBranchOptions
var ofBranchTrace = newNimNode(nnkOfBranch)
ofBranchTrace.add newIdentNode("HttpTrace")
ofBranchTrace.add caseStmtTraceBody
caseStmt.add ofBranchTrace
var ofBranchConnect = newNimNode(nnkOfBranch)
ofBranchConnect.add newIdentNode("HttpConnect")
ofBranchConnect.add caseStmtConnectBody
caseStmt.add ofBranchConnect
var ofBranchPatch = newNimNode(nnkOfBranch)
ofBranchPatch.add newIdentNode("HttpPatch")
ofBranchPatch.add caseStmtPatchBody
caseStmt.add ofBranchPatch
matchBody.add caseStmt
var matchProc = parseStmt("proc match(request: Request," &
"response: jester.Response): Future[bool] {.async, gcsafe.} = discard")
matchProc[0][6] = matchBody
result.add(outsideStmts)
result.add(matchProc)
result.add parseExpr("jester.serve(match, settings)")
#echo toStrLit(result)
#echo treeRepr(result)
macro settings*(body: untyped): typed =
#echo(treeRepr(body))
expectKind(body, nnkStmtList)
result = newStmtList()
# var settings = newSettings()
let settingsIdent = newIdentNode("settings")
result.add newVarStmt(settingsIdent, newCall("newSettings"))
for asgn in body.children:
expectKind(asgn, nnkAsgn)
result.add newAssignment(newDotExpr(settingsIdent, asgn[0]), asgn[1])