summaryrefslogtreecommitdiff
path: root/bin/serve.fnl
blob: b18d8427d9a73738ba0f41ef5ff4caab18800388 (plain)
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
(local fennel (require :vendor.fennel))

(when _G.unpack
 (tset table :unpack _G.unpack))

(fn ends-with [str end]
  (= (string.sub str (- (# end))) end))

(fn trim [str pattern]
  (local pattern (or pattern "%s"))
  (str:match (.. "^" pattern "*(.-)" pattern "*$")))

(fn file-exists [path]
  (local f (io.open path "r"))
  (and (~= f nil) (io.close f)))

(fn router [request]
  (local path
    (trim
     (if (ends-with request.path "/")
       (.. request.path "index")
       request.path)
     "/"))
  (local module-path (.. "pages." (string.gsub path "%." "/")))
  ;; FIXME: slow
  (if (file-exists (.. "pages/" path ".fnl"))
    (do
      (local (code headers html)
        ((. (require module-path) :render) request))
      (values code headers (.. "<!DOCTYPE html>\n" html)))
    (values 404 {:content-type "text/html"} "not found")))

(luna.router.route "GET /" router)
(luna.router.static "GET /static/" "static/")