Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set Content-Type header on Ring-Compojure application

I'm trying to get started with Clojure and Clojurescript by implementing a simple web app. Things are going pretty good so far and reading from different tutorials I've come up with the code below:

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 I can't display non-ascii characters on the page and I don't know how to set HTTP headers on a page.

I see solutions like this but I simply can't figure out where place them in my code:

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

P.S: Any suggestions about style and/or code organization are welcome.

like image 386
slhsen Avatar asked Feb 17 '14 16:02

slhsen


1 Answers

Use ring.util.response:

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

Then on your index function:

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

You can chain other actions on the response such as set-cookie and 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 "/"})))
like image 127
guilespi Avatar answered Oct 05 '22 08:10

guilespi