-
Notifications
You must be signed in to change notification settings - Fork 121
/
jester.nim
1456 lines (1276 loc) · 44.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
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (C) 2015 Dominik Picheta
# MIT License - Look at license.txt for details.
import net, strtabs, re, tables, os, strutils, uri,
times, mimetypes, asyncnet, asyncdispatch, macros, md5,
logging, httpcore, asyncfile, macrocache, json, options,
strformat
import jester/private/[errorpages, utils]
import jester/[request, patterns]
from cgi import decodeData, decodeUrl, CgiError
export request
export strtabs
export tables
export httpcore
export options
export MultiData
export HttpMethod
export asyncdispatch
export SameSite
when useHttpBeast:
import httpbeast except Settings, Request
import options
from nativesockets import close
else:
import asynchttpserver except Request
type
MatchProc* = proc (request: Request): Future[ResponseData] {.gcsafe, closure.}
MatchProcSync* = proc (request: Request): ResponseData{.gcsafe, closure.}
Matcher = object
case async: bool
of false:
syncProc: MatchProcSync
of true:
asyncProc: MatchProc
ErrorProc* = proc (
request: Request, error: RouteError
): Future[ResponseData] {.gcsafe, closure.}
MatchPair* = tuple
matcher: MatchProc
errorHandler: ErrorProc
MatchPairSync* = tuple
matcher: MatchProcSync
errorHandler: ErrorProc
Jester* = object
when not useHttpBeast:
httpServer*: AsyncHttpServer
settings: Settings
matchers: seq[Matcher]
errorHandlers: seq[ErrorProc]
MatchType* = enum
MRegex, MSpecial, MStatic
RawHeaders* = seq[tuple[key, val: string]]
ResponseHeaders* = Option[RawHeaders]
ResponseData* = tuple[
action: CallbackAction,
code: HttpCode,
headers: ResponseHeaders,
content: string,
matched: bool
]
CallbackAction* = enum
TCActionNothing, TCActionSend, TCActionRaw, TCActionPass
RouteErrorKind* = enum
RouteException, RouteCode
RouteError* = object
case kind*: RouteErrorKind
of RouteException:
exc: ref Exception
of RouteCode:
data: ResponseData
const jesterVer = "0.6.0"
proc toStr(headers: Option[RawHeaders]): string =
return $newHttpHeaders(headers.get(@({:})))
proc createHeaders(headers: RawHeaders): string =
result = ""
if headers.len > 0:
for header in headers:
let (key, value) = header
result.add(key & ": " & value & "\c\L")
result = result[0 .. ^3] # Strip trailing \c\L
proc createResponse(status: HttpCode, headers: RawHeaders): string =
return "HTTP/1.1 " & $status & "\c\L" & createHeaders(headers) & "\c\L\c\L"
proc unsafeSend(request: Request, content: string) =
when useHttpBeast:
request.getNativeReq.unsafeSend(content)
else:
# TODO: This may cause issues if we send too fast.
asyncCheck request.getNativeReq.client.send(content)
proc newCompletedFuture(): Future[void] =
result = newFuture[void]()
complete(result)
proc send(
request: Request, code: HttpCode, headers: Option[RawHeaders], body: string
): Future[void] =
when useHttpBeast:
let h =
if headers.isNone: ""
else: headers.get().createHeaders
request.getNativeReq.send(code, body, h)
return newCompletedFuture()
else:
return request.getNativeReq.respond(
code, body, newHttpHeaders(headers.get(@({:})))
)
proc statusContent(request: Request, status: HttpCode, content: string,
headers: Option[RawHeaders]): Future[void] =
try:
result = send(request, status, headers, content)
when not defined(release):
logging.debug(" $1 $2" % [$status, toStr(headers)])
except:
result = newCompletedFuture()
logging.error("Could not send response: $1" % osErrorMsg(osLastError()))
# TODO: Add support for proper Future Streams instead of this weird raw mode.
template enableRawMode* =
# TODO: Use the effect system to make this implicit?
result.action = TCActionRaw
proc send*(request: Request, content: string) =
## Sends ``content`` immediately to the client socket.
##
## Routes using this procedure must enable raw mode.
unsafeSend(request, content)
proc sendHeaders*(request: Request, status: HttpCode,
headers: RawHeaders) =
## 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``.
let headerData = createResponse(status, headers)
try:
request.send(headerData)
logging.debug(" $1 $2" % [$status, $headers])
except:
logging.error("Could not send response: $1" % [osErrorMsg(osLastError())])
proc sendHeaders*(request: Request, status: HttpCode) =
## Sends ``status`` and ``Content-Type: text/html`` as the headers to the
## client socket immediately.
let headers = @({"Content-Type": "text/html;charset=utf-8"})
request.sendHeaders(status, headers)
proc sendHeaders*(request: Request) =
## Sends ``Http200`` and ``Content-Type: text/html`` as the headers to the
## client socket immediately.
request.sendHeaders(Http200)
proc send*(request: Request, status: HttpCode, headers: RawHeaders,
content: string) =
## Sends out a HTTP response comprising of the ``status``, ``headers`` and
## ``content`` specified.
var headers = headers & @({"Content-Length": $content.len})
request.sendHeaders(status, headers)
request.send(content)
# TODO: Cannot capture 'paths: varargs[string]' here.
proc sendStaticIfExists(
req: Request, paths: seq[string]
): Future[HttpCode] {.async.} =
result = Http200
for p in paths:
if existsFile(p):
var fp = getFilePermissions(p)
if not fp.contains(fpOthersRead):
return Http403
let fileSize = getFileSize(p)
let ext = p.splitFile.ext
let mimetype = req.settings.mimes.getMimetype(
if ext.len > 0: ext[1 .. ^1]
else: ""
)
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 req.statusContent(Http304, "", none[RawHeaders]())
else:
await req.statusContent(Http200, file, some(@({
"Content-Type": mimetype,
"ETag": hashed
})))
else:
let headers = @({
"Content-Type": mimetype,
"Content-Length": $fileSize
})
await req.statusContent(Http200, "", some(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:
req.unsafeSend(value)
else:
break
file.close()
return
# If we get to here then no match could be found.
return Http404
proc close*(request: Request) =
## Closes client socket connection.
##
## Routes using this procedure must enable raw mode.
let nativeReq = request.getNativeReq()
when useHttpBeast:
nativeReq.forget()
nativeReq.client.close()
proc defaultErrorFilter(error: RouteError): ResponseData =
case error.kind
of RouteException:
let e = error.exc
let traceback = getStackTrace(e)
var errorMsg = e.msg
if errorMsg.len == 0: errorMsg = "(empty)"
let error = traceback & errorMsg
logging.error(error)
result.headers = some(@({
"Content-Type": "text/html;charset=utf-8"
}))
result.content = routeException(
error.replace("\n", "<br/>\n"),
jesterVer
)
result.code = Http502
result.matched = true
result.action = TCActionSend
of RouteCode:
result.headers = some(@({
"Content-Type": "text/html;charset=utf-8"
}))
result.content = error(
$error.data.code,
jesterVer
)
result.code = error.data.code
result.matched = true
result.action = TCActionSend
proc initRouteError(exc: ref Exception): RouteError =
RouteError(
kind: RouteException,
exc: exc
)
proc initRouteError(data: ResponseData): RouteError =
RouteError(
kind: RouteCode,
data: data
)
proc dispatchError(
jes: Jester,
request: Request,
error: RouteError
): Future[ResponseData] {.async.} =
for errorProc in jes.errorHandlers:
let data = await errorProc(request, error)
if data.matched:
return data
return defaultErrorFilter(error)
proc dispatch(
self: Jester,
req: Request
): Future[ResponseData] {.async.} =
for matcher in self.matchers:
if matcher.async:
let data = await matcher.asyncProc(req)
if data.matched:
return data
else:
let data = matcher.syncProc(req)
if data.matched:
return data
proc handleFileRequest(
jes: Jester, req: Request
): Future[ResponseData] {.async.} =
# Find static file.
# TODO: Caching.
# no need to normalize staticDir since it is normalized in `newSettings`
let path = jes.settings.staticDir / normalizedPath(
cgi.decodeUrl(req.pathInfo)
)
# Verify that this isn't outside our static dir.
var status = Http400
let pathDir = path.splitFile.dir & (if path.splitFile.dir[^1] == DirSep: "" else: $DirSep)
let staticDir = jes.settings.staticDir & (if jes.settings.staticDir[^1] == DirSep: "" else: $DirSep)
if pathDir.startsWith(staticDir):
if existsDir(path):
status = await sendStaticIfExists(
req,
@[path / "index.html", path / "index.htm"]
)
else:
status = await sendStaticIfExists(req, @[path])
# Http200 means that the data was sent so there is nothing else to do.
if status == Http200:
result[0] = TCActionRaw
when not defined(release):
logging.debug(" -> $1" % path)
return
return (TCActionSend, status, none[seq[(string, string)]](), "", true)
proc handleRequestSlow(
jes: Jester,
req: Request,
respDataFut: Future[ResponseData] | ResponseData,
dispatchedError: bool
): Future[void] {.async.} =
var dispatchedError = dispatchedError
var respData: ResponseData
# httpReq.send(Http200, "Hello, World!", "")
when respDataFut is Future[ResponseData]:
yield respDataFut
if respDataFut.failed:
# Handle any errors by showing them in the browser.
# TODO: Improve the look of this.
let exc = respDataFut.readError()
respData = await dispatchError(jes, req, initRouteError(exc))
dispatchedError = true
else:
respData = respDataFut.read()
else:
respData = respDataFut
# TODO: Put this in a custom matcher?
if not respData.matched:
respData = await handleFileRequest(jes, req)
case respData.action
of TCActionSend:
if (respData.code.is4xx or respData.code.is5xx) and
not dispatchedError and respData.content.len == 0:
respData = await dispatchError(jes, req, initRouteError(respData))
await statusContent(
req,
respData.code,
respData.content,
respData.headers
)
else:
when not defined(release):
logging.debug(" $1" % [$respData.action])
# Cannot close the client socket. AsyncHttpServer may be keeping it alive.
proc handleRequest(jes: Jester, httpReq: NativeRequest): Future[void] =
var req = initRequest(httpReq, jes.settings)
try:
when not defined(release):
logging.debug("$1 $2" % [$req.reqMethod, req.pathInfo])
if likely(jes.matchers.len == 1 and not jes.matchers[0].async):
let respData = jes.matchers[0].syncProc(req)
if likely(respData.matched):
return statusContent(
req,
respData.code,
respData.content,
respData.headers
)
else:
return handleRequestSlow(jes, req, respData, false)
else:
return handleRequestSlow(jes, req, dispatch(jes, req), false)
except:
let exc = getCurrentException()
let respDataFut = dispatchError(jes, req, initRouteError(exc))
return handleRequestSlow(jes, req, respDataFut, true)
assert(not result.isNil, "Expected handleRequest to return a valid future.")
proc newSettings*(
port = Port(5000), staticDir = getCurrentDir() / "public",
appName = "", bindAddr = "", reusePort = false, maxBody = 8388608, numThreads = 0,
futureErrorHandler: proc (fut: Future[void]) {.closure, gcsafe.} = nil
): Settings =
result = Settings(
staticDir: normalizedPath(staticDir),
appName: appName,
port: port,
bindAddr: bindAddr,
reusePort: reusePort,
maxBody: maxBody,
numThreads: numThreads,
futureErrorHandler: futureErrorHandler
)
proc register*(self: var Jester, matcher: MatchProc) =
## Adds the specified matcher procedure to the specified Jester instance.
self.matchers.add(
Matcher(
async: true,
asyncProc: matcher
)
)
proc register*(self: var Jester, matcher: MatchProcSync) =
## Adds the specified matcher procedure to the specified Jester instance.
self.matchers.add(
Matcher(
async: false,
syncProc: matcher
)
)
proc register*(self: var Jester, errorHandler: ErrorProc) =
## Adds the specified error handler procedure to the specified Jester instance.
self.errorHandlers.add(errorHandler)
proc initJester*(
settings: Settings = newSettings()
): Jester =
result.settings = settings
result.settings.mimes = newMimetypes()
result.matchers = @[]
result.errorHandlers = @[]
proc initJester*(
pair: MatchPair,
settings: Settings = newSettings()
): Jester =
result = initJester(settings)
result.register(pair.matcher)
result.register(pair.errorHandler)
proc initJester*(
pair: MatchPairSync, # TODO: Annoying nim bug: `MatchPair | MatchPairSync` doesn't work.
settings: Settings = newSettings()
): Jester =
result = initJester(settings)
result.register(pair.matcher)
result.register(pair.errorHandler)
proc initJester*(
matcher: MatchProc,
settings: Settings = newSettings()
): Jester =
result = initJester(settings)
result.register(matcher)
proc initJester*(
matcher: MatchProcSync,
settings: Settings = newSettings()
): Jester =
result = initJester(settings)
result.register(matcher)
proc serve*(
self: var Jester
) =
## Creates a new async http server instance and registers
## it with the dispatcher.
##
## The event loop is executed by this function, so it will block forever.
# 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)
assert self.settings.staticDir.len > 0, "Static dir cannot be an empty string."
if self.settings.bindAddr.len > 0:
logging.info("Jester is making jokes at http://$1:$2$3" %
[
self.settings.bindAddr, $self.settings.port, self.settings.appName
]
)
else:
when defined(windows):
logging.info("Jester is making jokes at http://127.0.0.1:$1$2 (all interfaces)" %
[$self.settings.port, self.settings.appName])
else:
logging.info("Jester is making jokes at http://0.0.0.0:$1$2" %
[$self.settings.port, self.settings.appName])
var jes = self
when useHttpBeast:
run(
proc (req: httpbeast.Request): Future[void] =
{.gcsafe.}:
result = handleRequest(jes, req),
httpbeast.initSettings(self.settings.port, self.settings.bindAddr, self.settings.numThreads)
)
else:
self.httpServer = newAsyncHttpServer(reusePort=self.settings.reusePort, maxBody=self.settings.maxBody)
let serveFut = self.httpServer.serve(
self.settings.port,
proc (req: asynchttpserver.Request): Future[void] {.gcsafe, closure.} =
result = handleRequest(jes, req),
self.settings.bindAddr)
if not self.settings.futureErrorHandler.isNil:
serveFut.callback = self.settings.futureErrorHandler
else:
asyncCheck serveFut
runForever()
template setHeader*(headers: var ResponseHeaders, key, value: string): typed =
## Sets a response header using the given key and value.
## Overwrites if the header key already exists.
bind isNone
if isNone(headers):
headers = some(@({key: value}))
else:
block outer:
# Overwrite key if it exists.
var h = headers.get()
for i in 0 ..< h.len:
if h[i][0] == key:
h[i][1] = value
headers = some(h)
break outer
# Add key if it doesn't exist.
headers = some(h & @({key: value}))
template resp*(code: HttpCode,
headers: openarray[tuple[key, val: string]],
content: string): typed =
## Sets ``(code, headers, content)`` as the response.
bind TCActionSend
result = (TCActionSend, code, result[2], content, true)
for header in headers:
setHeader(result[2], header[0], header[1])
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, newHttpHeaders, strtabs.`[]=`
result[0] = TCActionSend
result[1] = Http200
setHeader(result[2], "Content-Type", contentType)
result[3] = content
# This will be set by our macro, so this is here for those not using it.
result.matched = true
break route
template resp*(content: JsonNode): typed =
## Serializes ``content`` as the response, sets ``Http200`` as status code
## and "application/json" Content-Type.
resp($content, contentType="application/json")
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, newHttpHeaders
result[0] = TCActionSend
result[1] = code
setHeader(result[2], "Content-Type", contentType)
result[3] = content
result.matched = true
break route
template resp*(code: HttpCode): typed =
## Responds with the specified ``HttpCode``. This ensures that error handlers
## are called.
bind TCActionSend, newHttpHeaders
result[0] = TCActionSend
result[1] = code
result.matched = true
break route
template redirect*(url: string, halt = true): typed =
## Redirects to ``url``. Returns from this request handler immediately.
##
## If ``halt`` is true, skips executing future handlers, too.
##
## Any set response headers are preserved for this request.
bind TCActionSend, newHttpHeaders
result[0] = TCActionSend
result[1] = Http303
setHeader(result[2], "Location", url)
result[3] = ""
result.matched = true
if halt:
break allRoutes
else:
break route
template pass*(): typed =
## Skips this request handler.
##
## If you want to stop this request from going further use ``halt``.
result.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: openarray[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, newHttpHeaders
result[0] = TCActionSend
result[1] = code
result[2] = some(@headers)
result[3] = content
result.matched = true
break allRoutes
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 =
## Instructs the browser that the response should be stored on disk
## rather than displayed in the browser.
var disposition = "attachment"
if filename != "":
disposition.add("; filename=\"" & extractFilename(filename) & "\"")
let ext = splitFile(filename).ext
let contentTypeSet =
isSome(result[2]) and result[2].get().toTable.hasKey("Content-Type")
if not contentTypeSet and ext != "":
setHeader(result[2], "Content-Type", getMimetype(request.settings.mimes, ext))
setHeader(result[2], "Content-Disposition", disposition)
template sendFile*(filename: string): typed =
## Sends the file at the specified filename as the response.
result[0] = TCActionRaw
let sendFut = sendStaticIfExists(request, @[filename])
yield sendFut
let status = sendFut.read()
if status != Http200:
raise newException(JesterError, "Couldn't send requested file: " & filename)
# This will be set by our macro, so this is here for those not using it.
result.matched = true
break route
template `@`*(s: string): untyped =
## Retrieves the parameter ``s`` from ``request.params``. ``""`` will be
## returned if parameter doesn't exist.
if s in params(request):
# TODO: Why does request.params not work? :(
# TODO: This is some weird bug with macros/templates, I couldn't
# TODO: reproduce it easily.
params(request)[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: 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)
template responseHeaders*(): var ResponseHeaders =
## Access the Option[RawHeaders] response headers
if result[2].isNone:
result[2] = some[RawHeaders](@[])
result[2]
proc daysForward*(days: int): DateTime =
## Returns a DateTime object referring to the current time plus ``days``.
return getTime().utc + initTimeInterval(days = days)
template setCookie*(headersOpt: var ResponseHeaders, name, value: string, expires="",
sameSite: SameSite=Lax, secure = false,
httpOnly = false, domain = "", path = "") =
let newCookie = makeCookie(name, value, expires, domain, path, secure, httpOnly, sameSite)
if isSome(headersOpt) and
(let headers = headersOpt.get(); headers.toTable.hasKey("Set-Cookie")):
headersOpt = some(headers & @({"Set-Cookie": newCookie}))
else:
setHeader(headersOpt, "Set-Cookie", newCookie)
template setCookie*(name, value: string, expires="",
sameSite: SameSite=Lax, secure = false,
httpOnly = false, domain = "", path = "") =
## Creates a cookie which stores ``value`` under ``name``.
##
## The SameSite argument determines the level of CSRF protection that
## you wish to adopt for this cookie. It's set to Lax by default which
## should protect you from most vulnerabilities. Note that this is only
## supported by some browsers:
## https://caniuse.com/#feat=same-site-cookie-attribute
responseHeaders.setCookie(name, value, expires, sameSite, secure, httpOnly, domain, path)
template setCookie*(name, value: string, expires: DateTime,
sameSite: SameSite=Lax, secure = false,
httpOnly = false, domain = "", path = "") =
## Creates a cookie which stores ``value`` under ``name``.
setCookie(name, value,
format(expires.utc, "ddd',' dd MMM yyyy HH:mm:ss 'GMT'"),
sameSite, secure, httpOnly, domain, path)
proc normalizeUri*(uri: string): string =
## Remove any trailing ``/``.
if uri[uri.len-1] == '/': result = uri[0 .. uri.len-2]
else: result = uri
# -- Macro
proc checkAction*(respData: var ResponseData): bool =
case respData.action
of TCActionSend, TCActionRaw:
result = true
of TCActionPass:
result = false
of TCActionNothing:
raise newException(
ValueError,
"Missing route action, did you forget to use `resp` in your route?"
)
proc skipDo(node: NimNode): NimNode {.compiletime.} =
if node.kind == nnkDo:
result = node[6]
else:
result = node
proc ctParsePattern(pattern, pathPrefix: 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)
if pathPrefix.len > 0:
result.addPattNode(
bindSym("NodeText"), # Node kind
newStrLitNode(pathPrefix), # Text
newIdentNode("false") # Optional?
)
for node in patt:
result.addPattNode(
case node.typ
of NodeText: bindSym("NodeText")
of NodeField: bindSym("NodeField"),
newStrLitNode(node.text),
newIdentNode(if node.optional: "true" else: "false"))
template setDefaultResp*() =
# TODO: bindSym this in the 'routes' macro and put it in each route
bind TCActionNothing, newHttpHeaders
result.action = TCActionNothing
result.code = Http200
result.content = ""
template declareSettings() {.dirty.} =
bind newSettings
when not declaredInScope(settings):
var settings = newSettings()
proc createJesterPattern(
routeNode, patternMatchSym: NimNode,
pathPrefix: string
): NimNode {.compileTime.} =
var ctPattern = ctParsePattern(routeNode[1].strVal, pathPrefix)
# -> let <patternMatchSym> = <ctPattern>.match(request.path)
return newLetStmt(patternMatchSym,
newCall(bindSym"match", ctPattern, parseExpr("request.pathInfo")))
proc escapeRegex(s: string): string =
result = ""
for i in s:
case i
# https://stackoverflow.com/a/400316/492186
of '.', '^', '$', '*', '+', '?', '(', ')', '[', '{', '\\', '|':
result.add('\\')
result.add(i)
else:
result.add(i)
proc createRegexPattern(
routeNode, reMatchesSym, patternMatchSym: NimNode,
pathPrefix: string
): NimNode {.compileTime.} =
# -> let <patternMatchSym> = find(request.pathInfo, <pattern>, <reMatches>)
var strNode = routeNode[1].copyNimTree()
strNode[1].strVal = escapeRegex(pathPrefix) & strNode[1].strVal
return newLetStmt(
patternMatchSym,
newCall(
bindSym"find",
parseExpr("request.pathInfo"),
strNode,
reMatchesSym
)
)
proc determinePatternType(pattern: NimNode): MatchType {.compileTime.} =
case pattern.kind
of nnkStrLit:
var patt = parsePattern(pattern.strVal)
if patt.len == 1 and patt[0].typ == NodeText:
return MStatic
else:
return MSpecial
of nnkCallStrLit:
expectKind(pattern[0], nnkIdent)
case ($pattern[0]).normalize
of "re": return MRegex
else:
macros.error("Invalid pattern type: " & $pattern[0])
else:
macros.error("Unexpected node kind: " & $pattern.kind)
proc createCheckActionIf(): NimNode =
var checkActionIf = parseExpr(
"if checkAction(result): result.matched = true; break routesList"
)
checkActionIf[0][0][0] = bindSym"checkAction"
return checkActionIf
proc createGlobalMetaRoute(routeNode, dest: NimNode) {.compileTime.} =
## Creates a ``before`` or ``after`` route with no pattern, i.e. one which
## will be always executed.
# -> block route: <ifStmtBody>
var innerBlockStmt = newStmtList(
newNimNode(nnkBlockStmt).add(newIdentNode("route"), routeNode[1].skipDo())
)
# -> block outerRoute: <innerBlockStmt>
var blockStmt = newNimNode(nnkBlockStmt).add(
newIdentNode("outerRoute"), innerBlockStmt)
dest.add blockStmt
proc createRoute(
routeNode, dest: NimNode, pathPrefix: string, isMetaRoute: bool = false
) {.compileTime.} =
## Creates code which checks whether the current request path
## matches a route.
##
## The `isMetaRoute` parameter determines whether the route to be created is
## one of either a ``before`` or an ``after`` 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(routeNode[1])
case patternType
of MStatic:
discard
of MSpecial:
dest.add createJesterPattern(routeNode, patternMatchSym, pathPrefix)
of MRegex:
dest.add reMatches
dest.add createRegexPattern(
routeNode, reMatchesSym, patternMatchSym, pathPrefix
)
var ifStmtBody = newStmtList()
case patternType
of MStatic: discard
of MSpecial:
# -> setPatternParams(request, ret.params)
ifStmtBody.add newCall(bindSym"setPatternParams", newIdentNode"request",
newDotExpr(patternMatchSym, newIdentNode"params"))
of MRegex:
# -> setReMatches(request, <reMatchesSym>)
ifStmtBody.add newCall(bindSym"setReMatches", newIdentNode"request",
reMatchesSym)
ifStmtBody.add routeNode[2].skipDo()
let checkActionIf =
if isMetaRoute:
parseExpr("break routesList")
else:
createCheckActionIf()
# -> block route: <ifStmtBody>; <checkActionIf>
var innerBlockStmt = newStmtList(
newNimNode(nnkBlockStmt).add(newIdentNode("route"), ifStmtBody),
checkActionIf
)
let ifCond =
case patternType
of MStatic:
infix(