summaryrefslogtreecommitdiff
path: root/cattrap/src/cattrap.nim
diff options
context:
space:
mode:
authorJJ2023-05-02 21:25:12 +0000
committerJJ2023-05-02 21:45:09 +0000
commit786703e10c51507fa212448fe9d4dcccdbc140ee (patch)
tree0fa4db46371f022689295193ac6ba50bec54d2ae /cattrap/src/cattrap.nim
parentf0f5c29ec7ff009100e063f38bebf613054f44d7 (diff)
Add my HTTP server wrapper
Diffstat (limited to 'cattrap/src/cattrap.nim')
-rw-r--r--cattrap/src/cattrap.nim36
1 files changed, 36 insertions, 0 deletions
diff --git a/cattrap/src/cattrap.nim b/cattrap/src/cattrap.nim
new file mode 100644
index 0000000..1f8c79e
--- /dev/null
+++ b/cattrap/src/cattrap.nim
@@ -0,0 +1,36 @@
+import std/[os, strutils]
+import prologue, regex
+
+const roll = readFile("src/rickroll.html")
+
+# note: prologue appears to deal with directory traversal for us, nice
+proc serve(ctx: Context, regex: Regex) {.async.} =
+ if regex in $ctx.request.headers["User-Agent"]:
+ resp roll
+ else:
+ try:
+ if ($ctx.request.path == "/"):
+ resp readFile(getCurrentDir() & "/index.html")
+ else:
+ resp readFile(getCurrentDir() & $ctx.request.path)
+ except IOError:
+ resp "<html><body><h1>404 Not Found</h1></body></html>"
+
+try:
+ let port = Port(paramStr(1).parseInt())
+ let regex = re(paramStr(2))
+ let settings = newSettings(port = port)
+ let app = newApp(settings)
+
+ # gcsafe for passing a global to a callback
+ proc thunk(ctx: Context) {.async, gcsafe.} =
+ yield serve(ctx, regex)
+
+ # match all requests
+ app.get("*$", thunk)
+ app.run()
+
+except ValueError, IndexDefect:
+ echo "usage: cattrap <port> <regex>"
+except OSError:
+ echo "cattrap: insufficient permissions, try a different port"