【问题标题】:How to set Content-Type header on Ring-Compojure application如何在 Ring-Compojure 应用程序上设置 Content-Type 标头
【发布时间】:2014-03-17 01:00:37
【问题描述】:

我正在尝试通过实现一个简单的网络应用程序来开始使用 Clojure 和 Clojurescript。到目前为止一切进展顺利,阅读不同的教程后,我得出了以下代码:

core.clj:

(ns myapp.core
(:require [compojure.core :as compojure]
          [compojure.handler :as handler]
          [compojure.route :as route]
          [myapp.controller :as controller]))

(compojure/defroutes app-routes
  (compojure/GET "/" [] controller/index)
  (route/resources "/public")
  (route/not-found "Not Found"))

(def app
  (handler/site app-routes))

controller.clj:

(ns myapp.controller
  (:use ring.util.response)
  (:require [myapp.models :as model]
            [myapp.templates :as template]))

(defn index
  "Index page handler"
  [req]
  (->> (template/home-page (model/get-things)) response))

模板.clj:

(ns myapp.templates
  (:use net.cgrand.enlive-html)
  (:require [myapp.models :as model]))


(deftemplate home-page "index.html" [things]
  [:li] (clone-for [thing things] (do->
                                   (set-attr 'data-id (:id thing))
                                   (content (:name thing)))))

问题是我无法在页面上显示非 ascii 字符,而且我不知道如何在页面上设置 HTTP 标头。

我看到了这样的解决方案,但我根本不知道它们在我的代码中的位置:

(defn app [request]
  {:status 200
   :headers {"Content-Type" "text/plain"}
   :body "Hello World"})

P.S:欢迎对样式和/或代码组织提出任何建议。

【问题讨论】:

    标签: clojure http-headers compojure ring


    【解决方案1】:

    使用ring.util.response:

    (require '[ring.util.response :as r])
    

    然后在你的index 函数上:

    (defn index
      "Index page handler"
      [req]
      (-> (r/response (->> (template/home-page (model/get-things)) response))
          (r/header "Content-Type" "text/html; charset=utf-8")))
    

    您可以在响应上链接其他操作,例如 set-cookie 和诸如此类:

    (defn index
      "Index page handler"
      [req]
      (-> (r/response (->> (template/home-page (model/get-things)) response))
          (r/header "Content-Type" "text/html; charset=utf-8")
          (r/set-cookie "your-cookie-name"
                        "" {:max-age 1
                            :path "/"})))
    

    【讨论】:

    • 感谢您的回答。这行得通,但稍作修正:我必须在 r/response 之后删除双箭头宏。
    • 像魅力一样工作!感谢您提供详细信息!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-02
    • 2019-04-19
    • 2011-01-04
    • 2013-07-22
    • 2013-12-10
    • 2015-05-05
    相关资源
    最近更新 更多