commit 7e178d05010e26b348859c704e7edd386c8dd6b0
parent 02db18d7c6c835d828fe570c5f9ed9366ac04238
Author: Daniel Barlow <dan@telent.net>
Date: Mon, 21 Jul 2025 22:48:46 +0100
support requests for static assets
Diffstat:
2 files changed, 24 insertions(+), 8 deletions(-)
diff --git a/main.fnl b/main.fnl
@@ -13,6 +13,8 @@
(local { : view } (require :fennel))
+(local post-index (site.for-pathname "data/blogs/telent.blog/posts/"))
+
(local handlers
[
#(if (= $2 "/")
@@ -23,6 +25,16 @@
:order {:date :descending}
:offset 0
})
+
+ #(case (string.match $2 "(/static/%g+)" 1)
+ pathname
+ (case (post-index:static-file pathname)
+ path
+ {
+ :command :sendfile
+ :pathname path
+ }))
+
#(case (string.match $2 "/(%d+)/(%d+)/" 1)
(year month)
(let [after (os.time {: year : month :day -2 })
@@ -75,7 +87,7 @@
)
-(local post-index (site.for-pathname "data/blogs/telent.blog/posts/"))
+
(fn dispatch [route stream]
(let [s { :write #(stream:write_chunk $2) } ]
@@ -94,6 +106,9 @@
(lcmark.convert (f:read "*a") "html" { :yaml_parser #($1) }))
)))
(stream:write_chunk "" true))
+ :sendfile
+ (with-open [f (io.open route.pathname :r)]
+ (stream:write_body_from_file f))
:search
(do
(stream:write_chunk "<p><ul>")
diff --git a/site.fnl b/site.fnl
@@ -114,10 +114,11 @@
(tset :body-offset (f:seek :cur 0))
(tset :date (and fields.date (parse-timestamp fields.date)))))))))))
-(fn static-path-ok? [basedir name]
+
+(fn static-path-if-safe [basedir name]
(let [prefix (realpath basedir)
- fullpath (realpath (.. basedir name))]
- (string.find fullpath prefix 1 true)))
+ fullpath (realpath (.. basedir name))]
+ (and (string.find fullpath prefix 1 true) fullpath)))
(fn for-pathname [path]
(let [posts (index-posts path)]
@@ -125,12 +126,12 @@
:get #(. posts $2)
:search (fn [_] posts)
:path path
- :static-file (fn [name]
- (and (static-path-ok? path name) name))
+ :static-file (fn [_ name]
+ (static-path-if-safe path name))
}))
(define-tests :static-path
- (expect (static-path-ok? "./" "/README.md"))
- (expect (not (static-path-ok? "./tests/" "../README.md"))))
+ (expect (static-path-if-safe "./" "/README.md"))
+ (expect (not (static-path-if-safe "./tests/" "../README.md"))))
{ : for-pathname }