Clean up path parsing; URI params to alist

This commit is contained in:
Jaidyn Ann 2023-05-25 15:59:10 -05:00
parent 20ea5d46ee
commit d27eed97e8

View File

@ -28,7 +28,7 @@
;; The default 404 response. ;; The default 404 response.
(defun http-404 (env path-items params) (defun http-404 (env path-items params)
'(404 (:content-type "text/plain") '(404 (:content-type "text/plain")
("uh-oh, I did a war crime!"))) ("404, you goddamn fool!")))
;; Respond to requests within the /u/* directory. ;; Respond to requests within the /u/* directory.
@ -42,11 +42,10 @@
;; Returns the response data for Clack, given the request data `env`. ;; Returns the response data for Clack, given the request data `env`.
(defun server (env) (defun server (env)
(let* ((path-split-? (str:split #\? (getf env :request-uri))) (let* ((path (pathname-sans-parameters (getf env :request-uri)))
(path (car path-split-?)) (params (pathname-parameters (getf env :request-uri)))
(params (cadr path-split-?))
(response-function (response-function
(or (assoc-by-path *directories* (pathname-components path)) (or (assoc-by-path (directories) (pathname-components path))
'("" . http-404))) '("" . http-404)))
;; So that response functions only deal with relative paths… ;; So that response functions only deal with relative paths…
(path-sans-response-root (path-sans-response-root
@ -98,6 +97,23 @@
(+ depth 1)))))) (+ depth 1))))))
;; Removes parameters from a URI pathname, returning the bare path.
;; "/path/a/b?a=1&b=3" → "/path/a/b"
(defun pathname-sans-parameters (path)
(car (str:split #\? path)))
;; Convert the parameters of a URI pathname into an associative list.
;; "/path/a/b?a=1&b=2&c=3" → (("a" . "1") ("b" . "2") ("c" . "3"))
(defun pathname-parameters (path)
(mapcar
(lambda (pair)
(let ((pair-items (str:split #\= pair)))
(cons (car pair-items)
(cadr pair-items))))
(str:split #\& (cadr (str:split #\? path)))))
;; Split a pathname into a list of its components. ;; Split a pathname into a list of its components.
;; "/u/bear/apple.txt" → '("u" "bear" "apple.txt") ;; "/u/bear/apple.txt" → '("u" "bear" "apple.txt")
(defun pathname-components (pathname) (defun pathname-components (pathname)