Skip to content

Instantly share code, notes, and snippets.

@kopos
Created September 16, 2019 09:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kopos/bc68f7036a98c881c827bf1b676184e0 to your computer and use it in GitHub Desktop.
Save kopos/bc68f7036a98c881c827bf1b676184e0 to your computer and use it in GitHub Desktop.
Unified URL management to respond to GET, POST & Websocket
; 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