Skip to content

Instantly share code, notes, and snippets.

@iantruslove
Last active August 29, 2015 14:05
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 iantruslove/e297320b4052f4278e52 to your computer and use it in GitHub Desktop.
Save iantruslove/e297320b4052f4278e52 to your computer and use it in GitHub Desktop.
Ring: from the ground up
(defn wrap-generic-middleware-example [handler & [other-args]]
(fn [request]
;; Early side-effects:
(log/info "Wrapping incoming request...")
(let [;; Modify request here:
req (assoc request :new-req-key "some value for handlers")
;; Run the handlers:
resp (handler req)]
;; Late side-effects:
(log/info "My middleware is almost done.")
;; Modify and return the response here:
(assoc resp :some-key "some value"))))
(defn hello-world-handler [req]
{:status 200
:headers {"content-type" "text/plain"}
:body (format "Hello, %s!\n" (:remote-addr req))})
(def request {:remote-addr "12.34.56.78" :uri "/" :request-method :get})
(hello-world-handler request)
;;=> {:status 200
;; :headers {"content-type" "text/plain"}
;; :body "Hello, 12.34.56.78!\n"}
(defn wrap-no-cache [handler]
(fn [request]
(let [response (handler request)]
(update-in response [:headers "cache-control"]
(fnil identity "no-cache")))))
(def app (wrap-no-cache hello-world-handler))
(app request)
;;=> {:status 200
;; :headers {"content-type" "text/plain"
;; "cache-control" "no-cache"}
;; :body "Hello, 12.34.56.78!\n"}
{:foo bar
;;TODO!!!!!
;;TODO!!!!!
}
{:status 200
:headers {"Content-Type" "application/json"
"Cache-Control" "no-cache"}
:body "{\"accountId\":27366391,\"balance\":23.21,\"currency\":\"USD\"}"}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment