Skip to content

Instantly share code, notes, and snippets.

@middlesphere
Created November 21, 2018 09:15
Show Gist options
  • Save middlesphere/589794a5ed2339e319f78a75a4332513 to your computer and use it in GitHub Desktop.
Save middlesphere/589794a5ed2339e319f78a75a4332513 to your computer and use it in GitHub Desktop.
Example usage of interceptors
(ns test01.core
(:gen-class)
(:require [org.httpkit.server :as kit]
[org.httpkit.client :as kit-client]
[sieppari.core :as sieppari]
[sieppari.context]
[muuntaja.interceptor]
[clojure.core.async :as a :refer [go chan <! <!! >! >!! timeout close! put! take! alts! alts!!]]
[reitit.ring :as ring]
[reitit.http :as http]
[reitit.core :as r]
[fipp.edn :refer (pprint)]
[reitit.interceptor.sieppari]))
(def <async> #(a/go %))
(def <sync> identity)
(def <thread> #(a/thread %))
(defn prn-tap [v]
(println v))
(add-tap prn-tap)
(defn interceptor [f x]
{:enter (fn [ctx] (f
(update-in ctx [:request :via] (fnil conj []) {:enter x
:thread (.getName (Thread/currentThread))})))
:leave (fn [ctx] (f
(update-in ctx [:response :body] conj {:leave x
:thread (.getName (Thread/currentThread))})))})
(defn handler [f data]
(fn [{:keys [via] :as request}]
(f
(do
(pprint (dissoc request :reitit.core/match :reitit.core/router))
{:status 200,
:body (conj via (str {:handler data
:thread (.getName (Thread/currentThread))}))}))))
(def routes (http/router [["/" {:get {:handler (handler <async> "root")}}]
["/test1"
["" {:name ::test1
:interceptors [(interceptor <sync> :test1)]
:get {:handler (handler <sync> "test1")}}]
["/test2" {:interceptors [(interceptor <async> :test2-level)]
:get {:interceptors [(interceptor <thread> :test2-get)]
:handler (handler <async> "test2")}}]]]))
;;(r/routes routes)
(def app (http/ring-handler routes
(ring/create-default-handler)
{:executor reitit.interceptor.sieppari/executor
:interceptors []}))
(app {:uri "/test1/test2"
:request-method :get})
(def params {:host "0.0.0.0" :port 8080})
(defn start-server
[handler params]
(kit/run-server handler params))
(defn -main "entry point"
[& args]
(start-server app params)
(println "server is started: " params))
;; ----------- client and repl zone---------------------------------------
(defn handle-response
[resp]
(println (:body resp)))
(comment
(def stop-fn (start-server app params))
(time (dotimes [_ 10]
(kit-client/get "http://localhost:8080" {:timeout 20000} handle-response)))
(time (slurp "http://localhost:8080/test1/test2"))
(stop-fn))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment