Created
February 14, 2018 16:22
-
-
Save ampersanda/83f43e55c06f84d93f3484b5edc4c356 to your computer and use it in GitHub Desktop.
Clojure Compojure Added Session Handler
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;; block 1 | |
(ns sessiontest.handler | |
(:use [ring.middleware.json :only (wrap-json-response)] | |
;; use json response | |
ring.middleware.session | |
;; use session | |
[ring.util.response :only (response)] | |
;; use response | |
[hiccup.middleware :only (wrap-base-url)]) | |
;; use hiccup | |
(:require [compojure.core :refer :all] | |
[compojure.route :as route] | |
[ring.middleware.defaults :refer [wrap-defaults site-defaults]] | |
[compojure.handler :as handler] | |
;; require handler | |
)) | |
;; block 2 | |
(defroutes app-routes | |
;; catch the :session (keyword) into session variable | |
(GET "/" {session :session} [] | |
;; catch :counter (keyword) inside the session (variable) to c (variable) if exists, otherwise use 0 (zero) to fill the value | |
(let [c (:counter session 0) | |
;; define the session (variable) with the old session which added :counter (keyword) inside and also increment the value | |
session (assoc session :counter (inc c))] | |
(-> | |
;; return the result as json | |
(response {:the_counter (:counter session)}) | |
;; re-new the session | |
(assoc :session session)))) | |
;; just handle when no route matched | |
(route/not-found "Not Found")) | |
;; block 3 | |
(def app | |
(-> (handler/site | |
app-routes {:session | |
{:cookie-name "counter-session" | |
:cookie-attrs | |
{:max-age 15 ;; expires in second | |
}}}) | |
(wrap-base-url) | |
(wrap-json-response) | |
(wrap-session)) | |
;; delete or comment this default command | |
;;(wrap-defaults app-routes site-defaults) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment