Support multiple sessions

This commit is contained in:
Michiel Borkent 2020-03-29 14:01:30 +02:00
parent 313971d0d7
commit 34d36d56ba

View file

@ -13,9 +13,14 @@
(def notes-file (io/file (System/getProperty "user.home") ".notes" "notes.txt")) (def notes-file (io/file (System/getProperty "user.home") ".notes" "notes.txt"))
(io/make-parents notes-file) (io/make-parents notes-file)
(def file-lock (Object.))
;; ensure notes file exists ;; ensure notes file exists
(spit notes-file "" :append true) (spit notes-file "" :append true)
(defn write-note! [note]
(locking file-lock
(spit notes-file (str note "\n") :append true)))
;; hiccup-like ;; hiccup-like
(defn html [v] (defn html [v]
(cond (vector? v) (cond (vector? v)
@ -101,11 +106,13 @@
;; run the server ;; run the server
(with-open [server-socket (let [s (new ServerSocket 8080)] (with-open [server-socket (let [s (new ServerSocket 8080)]
(println "Server started on port 8080.") (println "Server started on port 8080.")
s) s)]
client-socket (.accept server-socket)]
(loop [] (loop []
(let [out (io/writer (.getOutputStream client-socket)) (let [client-socket (.accept server-socket)]
is (.getInputStream client-socket) (future
(with-open [conn client-socket]
(let [out (io/writer (.getOutputStream conn))
is (.getInputStream conn)
in (io/reader is) in (io/reader is)
[_req & headers :as response] [_req & headers :as response]
(loop [headers []] (loop [headers []]
@ -125,7 +132,7 @@
_ (when-not (str/blank? form-data) _ (when-not (str/blank? form-data)
(when debug? (println form-data)) (when debug? (println form-data))
(let [note (str/replace form-data "note=" "")] (let [note (str/replace form-data "note=" "")]
(spit notes-file (str note "\n") :append true))) (write-note! note)))
_ (when debug? (println))] _ (when debug? (println))]
(cond (cond
;; if we didn't see this session before, we want the user to re-authenticate ;; if we didn't see this session before, we want the user to re-authenticate
@ -134,5 +141,5 @@
(basic-auth-response out uuid)) (basic-auth-response out uuid))
(not (authenticate! session-id headers)) (not (authenticate! session-id headers))
(basic-auth-response out session-id) (basic-auth-response out session-id)
:else (home-response out session-id))) :else (home-response out session-id))))))
(recur))) (recur)))