Skip to content

Instantly share code, notes, and snippets.

@reedho
Last active September 27, 2018 04:19
Show Gist options
  • Save reedho/e0926bd449f845907c76 to your computer and use it in GitHub Desktop.
Save reedho/e0926bd449f845907c76 to your computer and use it in GitHub Desktop.
Clojure Ring Basic, Etcetera...
;; Ring handler is just, just plain old function
(defn always-ok-handler [request]
"OK")
;; Attach one single handler per http-server instance
;; This http-server will always response with "OK" no matter what
;; request it was given.
(aleph.http.server/start-server always-ok-handler {:port 2222})
;; Compojure routes help us mapping request uri, methods to go
;; to where we want to.
(compojure.core/routes
(compojure.core/ANY "/index" [] "Hello there")
(compojure.core/GET "/motd" [] "Be safe, always be safe!"))
;; Above form will return a ring handler, so better we make ref for it.
(def simple-handler
(compojure.core/routes
(compojure.core/ANY "/index" [] "Hello there")
(compojure.core/GET "/motd" [] "Be safe, always be safe!")))
;; Yes, handler is just plain old function! Here you can check it its
;; do the job by just evaling it.
(simple-handler {:uri "/index"}) ;;=> {:status 200, :headers {"Content-Type" "text/html; charset=utf-8"}, :body "Hello there"}
(simple-handler {:uri "/motd"}) ;;=> nil
(simple-handler {:uri "/motd" :request-method :get}) ;;=> { ... :body "Be safe, always be safe!"}
;; Middleware testing
(let [req {:uri "/index.php"
:query-string "q=10"}]
((ring.middleware.params/wrap-params identity) req)) ;;=> {:uri ... :query-params {"q" 10} :params {"q" 10}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment