utils
This commit is contained in:
parent
0ef26fd7d7
commit
da3cd68519
50
server.lisp
50
server.lisp
|
@ -10,19 +10,7 @@
|
|||
(defun route-hello-world (env)
|
||||
(declare (ignore env))
|
||||
'(200 (:content-type "text/plain")
|
||||
("<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>Page Title</title>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<h1>My First Heading</h1>
|
||||
<p>My first paragraph.</p>
|
||||
|
||||
</body>
|
||||
</html>")))
|
||||
|
||||
("hello")))
|
||||
|
||||
(defun route-not-found (&optional env)
|
||||
(declare (ignore env))
|
||||
|
@ -42,40 +30,6 @@
|
|||
`(200 (:content-type ,mime-string) ,file-path))
|
||||
(route-not-found))))
|
||||
|
||||
;; --------------------------------------------
|
||||
(let ((ht (make-hash-table :test 'equal)))
|
||||
(setf (gethash "abc" ht) 233)
|
||||
(gethash "abc" ht))
|
||||
|
||||
(defun read-file-as-binary (file-path)
|
||||
(with-open-file (stream file-path :element-type '(unsigned-byte 8))
|
||||
(let ((buffer (make-array (file-length stream)
|
||||
:element-type '(unsigned-byte 8))))
|
||||
(read-sequence buffer stream)
|
||||
buffer)))
|
||||
|
||||
;; key is file-path, value is (vector '(unsigned-byte 8))
|
||||
(defparameter *file-cache* (make-hash-table :test 'equal))
|
||||
|
||||
(defun serve-static-file-with-cache (env)
|
||||
;; no expiration currently.
|
||||
(let* ((request-path (getf env :request-uri))
|
||||
(file-path (pathname (concatenate 'string
|
||||
+static-directory+
|
||||
(subseq request-path
|
||||
(length +static-prefix+)))))
|
||||
(cache-result (gethash file-path *file-cache*)))
|
||||
(if (or (gethash file-path *file-cache*) (probe-file file-path))
|
||||
(let ((mime-string (let ((mime (file-types:file-mime file-path)))
|
||||
(format nil "~A/~A" (nth 0 mime) (nth 1 mime)))))
|
||||
`(200 (:content-type ,mime-string)
|
||||
,(progn (if (not (gethash file-path *file-cache*))
|
||||
(progn (setf (gethash file-path *file-cache*)
|
||||
(read-file-as-binary file-path))))
|
||||
(gethash file-path *file-cache*))))
|
||||
(route-not-found))))
|
||||
|
||||
|
||||
(defun dispatch (request-path dispatch-table)
|
||||
;; path: request url
|
||||
;; dispatch-table: '(matcher function)
|
||||
|
@ -93,7 +47,7 @@
|
|||
|
||||
(defparameter +dispatch-table+
|
||||
`(("^/$" ,#'route-hello-world)
|
||||
(,(concatenate 'string "^" +static-prefix+ ".*$") ,#'serve-static-file-with-cache)
|
||||
(,(concatenate 'string "^" +static-prefix+ ".*$") ,#'serve-static-file)
|
||||
("^/binary$"
|
||||
,(lambda (env)
|
||||
(declare (ignore env))
|
||||
|
|
|
@ -0,0 +1,6 @@
|
|||
(defun read-file-as-binary (file-path)
|
||||
(with-open-file (stream file-path :element-type '(unsigned-byte 8))
|
||||
(let ((buffer (make-array (file-length stream)
|
||||
:element-type '(unsigned-byte 8))))
|
||||
(read-sequence buffer stream)
|
||||
buffer)))
|
Loading…
Reference in New Issue