From 5210b2c5c4e30c5cd1ce555f1f0b8b6789816395 Mon Sep 17 00:00:00 2001 From: Tommi Reiman Date: Sat, 25 Aug 2018 16:28:57 +0300 Subject: [PATCH] reitit-http example --- examples/http/README.md | 7 ++++- examples/http/project.clj | 1 + examples/http/src/example/server.clj | 39 ++++++++++++++++++++++++---- 3 files changed, 41 insertions(+), 6 deletions(-) diff --git a/examples/http/README.md b/examples/http/README.md index 3fe225c4..a387b472 100644 --- a/examples/http/README.md +++ b/examples/http/README.md @@ -7,7 +7,12 @@ (start) ``` -Go with browser to http://localhost:3000 +Go with browser to: + +* http://localhost:3000/api/sync - synchronous +* http://localhost:3000/api/async - with core.async +* http://localhost:3000/api/future - with futures + ## License diff --git a/examples/http/project.clj b/examples/http/project.clj index 60f6406d..ac1c52e3 100644 --- a/examples/http/project.clj +++ b/examples/http/project.clj @@ -1,6 +1,7 @@ (defproject ring-example "0.1.0-SNAPSHOT" :description "Reitit Ring App with Swagger" :dependencies [[org.clojure/clojure "1.9.0"] + [org.clojure/core.async "0.4.474"] [ring "1.6.3"] [metosin/reitit "0.2.0-SNAPSHOT"]] :repl-options {:init-ns example.server}) diff --git a/examples/http/src/example/server.clj b/examples/http/src/example/server.clj index 17f4f694..995bb9e2 100644 --- a/examples/http/src/example/server.clj +++ b/examples/http/src/example/server.clj @@ -1,17 +1,46 @@ (ns example.server (:require [reitit.http :as http] [reitit.ring :as ring] + [clojure.core.async :as a] [reitit.interceptor.sieppari] [ring.adapter.jetty :as jetty])) +(defn -interceptor [f x] + {:enter (fn [ctx] (f (update-in ctx [:request :via] (fnil conj []) x))) + :leave (fn [ctx] (f (update-in ctx [:response :body] str "\n<- " x)))}) + +(def interceptor (partial -interceptor identity)) +(def future-interceptor (partial -interceptor #(future %))) +(def async-interceptor (partial -interceptor #(a/go %))) + +(defn -handler [f {:keys [via]}] + (f {:status 200, + :body (str (apply str (map #(str "-> " % "\n") via)) " hello!")})) + +(def handler (partial -handler identity)) +(def future-handler (partial -handler #(future %))) +(def async-handler (partial -handler #(a/go %))) + (def app (http/ring-handler (http/router - ["/" {:get (fn [request] - {:status 200 - :body "hello!"})}]) - (ring/routes - (ring/create-default-handler)) + ["/api" + {:interceptors [(interceptor :api)]} + + ["/sync" + {:interceptors [(interceptor :sync)] + :get {:interceptors [(interceptor :hello)] + :handler handler}}] + + ["/async" + {:interceptors [(async-interceptor :async)] + :get {:interceptors [(async-interceptor :async-hello)] + :handler async-handler}}] + ["/future" + {:interceptors [(future-interceptor :sync)] + :get {:interceptors [(future-interceptor :hello)] + :handler future-handler}}]]) + (ring/create-default-handler) {:executor reitit.interceptor.sieppari/executor})) (defn start []