How to set Content-Type header in Ring-Compojure app

I am trying to get started with Clojure and Clojurescript by implementing a simple web application. Everything is fine so far, and I read from various lessons, I came up with the following code:

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))

templates.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)))))

The problem is that I cannot display non-ascii characters on the page, and I don't know how to set the HTTP headers on the page.

I see such solutions, but I just can't figure out where to put them in my code:

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

PS: Any suggestions about the style and / or organization of the code are welcome.

+4
source share
1 answer

Use ring.util.response:

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

Then in your function 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 whatnot:

(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 "/"})))
+10

Source: https://habr.com/ru/post/1527344/


All Articles