在 clojure-ring 中清除会话(注销用户)

clearing a session (logging a user out) in clojure-ring

简单地将请求映射的 :session 设置为 nil 会导致注销,我的代码如下所示:

(GET "/logout" [ :as request] 
  (if-let [useremail (get-in request [:session :ph-auth-email])]
    (-> (response {:status 200,
                   :body (pr-str "logged out " useremail),
                   :headers {"Content-Type:" "text/html"}})
        (assoc request [:session nil]))))

但是我得到一个错误:

java.lang.Thread.run(Thread.java:745)

2015-02-18 09:29:05.134:WARN:oejs.AbstractHttpConnection:/logout

java.lang.Exception: Unrecognized body: {:status 200, :body "\"logged out \" \"sova\"", :headers {"Content-Type:" "text/html"}}

ring.util.response/response expects only the body as parameter since it'll build :status and :headers around it (see here)。但是,映射不是有效主体 - 仅允许使用字符串、文件和流。

所以,这就是导致异常的原因;现在,关于您的问题:您可以通过在 响应 (source) 中将 :session 设置为 nil 来注销用户 - 这会减少您的代码为:

(GET "/logout" [:as request] 
  (if-let [useremail (get-in request [:session :ph-auth-email])]
    {:status 200,
     :body (pr-str "logged out " useremail),
     :session nil, ;; !!!
     :headers {"Content-Type" "text/html"}}))