Examples for Clojure Ring (#6881)

This commit is contained in:
Graham Cox 2019-05-24 17:24:47 +01:00 committed by Grzegorz Piwowarek
parent 4864f0bc45
commit c90f76a4f8
4 changed files with 84 additions and 0 deletions

12
clojure/ring/.gitignore vendored Normal file
View File

@ -0,0 +1,12 @@
/target
/classes
/checkouts
profiles.clj
pom.xml
pom.xml.asc
*.jar
*.class
/.lein-*
/.nrepl-port
.hgignore
.hg/

16
clojure/ring/README.md Normal file
View File

@ -0,0 +1,16 @@
# Clojure Ring Examples
This project acts as a set of examples for the Clojure Ring library.
## Runing the examples
The examples can all be run from the Leiningen REPL.
Firstly, start the REPL with `lein repl`. Then the examples can be executed with:
* `(run simple-handler)` - A simple handler that just echos a constant string to the client
* `(run check-ip-handler)` - A handler that echos the clients IP Address back to them
* `(run echo-handler)` - A handler that echos the value of the "input" parameter back
* `(run request-count-handler)` - A handler with a session that tracks how many times this session has requested this handler
In all cases, the handlers can be accessed on http://localhost:3000.

8
clojure/ring/project.clj Normal file
View File

@ -0,0 +1,8 @@
(defproject baeldung-ring "0.1.0-SNAPSHOT"
:dependencies [[org.clojure/clojure "1.10.0"]
[ring/ring-core "1.7.1"]
[ring/ring-jetty-adapter "1.7.1"]
[ring/ring-devel "1.7.1"]]
:plugins [[lein-ring "0.12.5"]]
:ring {:handler ring.core/simple-handler}
:repl-options {:init-ns ring.core})

View File

@ -0,0 +1,48 @@
(ns ring.core
(:use ring.adapter.jetty
[ring.middleware.content-type]
[ring.middleware.cookies]
[ring.middleware.params]
[ring.middleware.session]
[ring.middleware.session.cookie]
[ring.util.response]))
;; Handler that just echos back the string "Hello World"
(defn simple-handler [request]
{:status 200
:headers {"Content-Type" "text/plain"}
:body "Hello World"})
;; Handler that echos back the clients IP Address
;; This demonstrates building responses properly, and extracting values from the request
(defn check-ip-handler [request]
(content-type
(response (:remote-addr request))
"text/plain"))
;; Handler that echos back the incoming parameter "input"
;; This demonstrates middleware chaining and accessing parameters
(def echo-handler
(-> (fn [{params :params}]
(content-type
(response (get params "input"))
"text/plain"))
(wrap-params {:encoding "UTF-8"})
))
;; Handler that keeps track of how many times each session has accessed the service
;; This demonstrates cookies and sessions
(def request-count-handler
(-> (fn [{session :session}]
(let [count (:count session 0)
session (assoc session :count (inc count))]
(-> (response (str "You accessed this page " count " times."))
(assoc :session session))))
wrap-cookies
(wrap-session {:cookie-attrs {:max-age 3600}})
))
;; Run the provided handler on port 3000
(defn run
[h]
(run-jetty h {:port 3000}))