Created
September 16, 2019 09:22
-
-
Save kopos/bc68f7036a98c881c827bf1b676184e0 to your computer and use it in GitHub Desktop.
Unified URL management to respond to GET, POST & Websocket
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
; deps | |
; | |
; [org.clojure/clojure "1.10.0"] | |
; [http-kit "2.3.0"] | |
; [ring "1.7.1"] | |
; [compojure "1.6.1"] | |
(ns unified.core | |
(:require | |
[ring.middleware.params :refer [wrap-params]] | |
[compojure.core :refer :all] | |
[org.httpkit.server :refer :all]) | |
(:gen-class)) | |
(defn uid [] (.toString (java.util.UUID/randomUUID))) | |
(def channel-hub (atom {})) | |
(defn- broadcast | |
([txt] | |
(broadcast txt nil)) | |
([txt chid] | |
(doseq [[uid channel] @channel-hub] | |
(println uid) | |
(if (= chid uid) | |
(send! channel (str "You sent: " txt)) | |
(send! channel (str uid " sent: " txt)))))) | |
(defn status [request] | |
{:status 200 | |
:headers {"Content-Type" "text/plain"} | |
:body "Hello World!"}) | |
(defn handler [request] | |
(let [uid (get-in request [:params "uid"]) | |
txt (get-in request [:params "txt"])] | |
(println uid txt) | |
(broadcast txt uid) | |
{:status 200 | |
:headers {"Content-Type" "text/plain"} | |
:body "Txts sent!"})) | |
(defn unified [request] | |
(let [chid (uid)] | |
(with-channel request channel | |
(if (websocket? channel) | |
(do | |
(println chid) | |
(swap! channel-hub assoc chid channel) | |
(send! channel (str "Welcome. Your Channel: " chid)) | |
(on-receive channel #(broadcast % chid))) | |
(let [res (case (:request-method request) | |
:post (handler request) | |
:get (status request) | |
:default nil)] | |
(send! channel res)))))) | |
(defroutes app | |
(ANY "/" [] (wrap-params unified))) | |
(defn -main [& args] | |
(run-server app {:port 8080})) | |
; Test POST | |
; curl -i -X POST http://localhost:8080/?txt=<random text>&uid=<chid> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment