Skip to content

Commit

Permalink
sse backend handler
Browse files Browse the repository at this point in the history
  • Loading branch information
nohaapav committed Oct 28, 2017
1 parent e6df0da commit e144887
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
5 changes: 5 additions & 0 deletions src/clj/swarmpit/handler.clj
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,11 @@
([response] {:status 201
:body response}))

(defn resp-accepted
([] {:status 202})
([response] {:status 202
:body response}))

;;; Handler

(defmulti dispatch identity)
Expand Down
30 changes: 30 additions & 0 deletions src/clj/swarmpit/handler_sse.clj
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
(ns swarmpit.handler-sse
(:require [org.httpkit.server :refer [run-server with-channel on-close send! close]]
[swarmpit.handler :refer [dispatch resp-accepted resp-error]]))

(def channel-hub (atom {}))

(defn broadcast [message]
(doseq [channel (keys @channel-hub)]
(send! channel message false)))

(defmethod dispatch :events [_]
(fn [req]
(with-channel req channel
(send! channel {:status 200
:headers {"Content-Type" "text/event-stream"
"Access-Control-Allow-Origin" "*"
"Cache-Control" "no-cache"
"Connection" "keep-alive"}
:body ":ok\n\n"} false)
(swap! channel-hub assoc channel req)
(on-close channel (fn [_]
(swap! channel-hub dissoc channel))))))

(defmethod dispatch :event-push [_]
(fn [{:keys [params]}]
(if (some? params)
(do
(broadcast (str "data: " params "\n\n"))
(resp-accepted (str "Broadcasted to " (count @channel-hub) " clients")))
(resp-error 400 "No event data send"))))

0 comments on commit e144887

Please sign in to comment.