Skip to content

Instantly share code, notes, and snippets.

@arathunku
Last active August 29, 2015 14:23
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save arathunku/b1e49713fb4084262f03 to your computer and use it in GitHub Desktop.
(ns gs.handler
(:require
[compojure.core :as compojure :refer [GET]]
[ring.middleware.params :as params]
[compojure.route :as route]
[aleph.http :as http]
[manifold.stream :as s]
[manifold.deferred :as d]
[clojure.core.async :as a]))
(def non-websocket-request
{:status 400
:headers {"content-type" "application/text"}
:body "Expected a websocket request."})
(defn echo-handler
"This is another asynchronous handler, but uses `let-flow` instead of `chain` to define the
handler in a way that at least somewhat resembles the synchronous handler."
[req]
(->
(d/let-flow [conn (http/websocket-connection req)]
(d/loop []
(->
(d/let-flow [msg (s/take! conn ::none)]
(when-not (= ::none msg)
(do
(println msg)
(d/let-flow [result (s/put! conn msg)]
(when result
(d/recur))))))
(d/catch
(fn [ex]
(s/put! conn (str "ERROR: " ex))
(s/close! conn))))))
(d/catch
(fn [_]
non-websocket-request))))
(def app
(params/wrap-params
(compojure/routes
(GET "/echo" [] echo-handler)
(route/not-found "No such page."))))
(ns gs.repl
(:require [aleph.http :as http])
(:use gs.handler))
(defn get-handler []
(-> #'app))
(defn start-server (http/start-server (get-handler) {:port 8080}))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment