summaryrefslogtreecommitdiff
path: root/bin/serve.fnl
blob: 823546828b15be1adee837da7984ac9f6c8596cc (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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
(local fennel (require :vendor.fennel))

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

(set _G.reload
  (fn [module]
    (local old (require module))
    (tset package :loaded module nil)
    (local (ok? new) (pcall require module))
    (if (not ok?)
      (do
       (tset package :loaded module old)
       (error new))
      (when (= (type new) :table)
       (do
        (each [k v (pairs new)]
              (tset old k v))
        (each [k (pairs old)]
              (when (not (. new k))
                (tset old k nil)))
        (tset package :loaded module old))))))

(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]
  (let
    [path (trim
            (if (ends-with request.path "/")
              (.. request.path "index")
              request.path)
            "/")
     module-path (.. "pages." (string.gsub path "%." "/"))
     module-exists? (file-exists? (.. "pages/" path ".fnl"))]
    ;; FIXME: slow
    (if module-exists?
      (let [(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/")

(when luna.debug
  (luna.evalfn (fn [code] (fennel.eval code {:env _G}))))