Skip to content

Instantly share code, notes, and snippets.

@BrainBacon
Created October 4, 2012 22:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BrainBacon/3836907 to your computer and use it in GitHub Desktop.
Save BrainBacon/3836907 to your computer and use it in GitHub Desktop.
Cheshire binding in middleman
(ns pitchit.server
(:require [cheshire.core :as json]
[cheshire.factory :as factory]
[noir.server :as server]
[pitchit.views common welcome]
[pitchit.models db]))
(server/load-views-ns 'pitchit.views)
(defn -main [& m]
(let [mode (keyword (or (first m) :dev))
port (Integer. (get (System/getenv) "PORT" "8081"))]
(server/start port {:mode mode
:ns 'it354})))
(defn fix-base-url [handler]
(fn [request]
(with-redefs [noir.options/resolve-url
(fn [url]
;prepend context to the relative URLs
(if (.contains url "://")
url (str (:context request) url)))]
(handler request))))
(defn json-update [json]
(binding [factory/*json-factory* (factory/make-json-factory
{:allow-unquoted-field-names true
:allow-single-quotes true})]
(json/decode json true)))
(defn json-body [handler]
(fn [req]
(let [neue (if (= "application/json" (get-in req [:headers "content-type"]))
(update-in req [:params] merge (json-update (slurp (:body req)))) req)]
(handler neue))))
(server/add-middleware json-body)
(def base-handler
(server/gen-handler {:ns 'pitchit}))
(def handler (-> base-handler fix-base-url))
(comment
;test code
(def myServer
(server/start 8081))
(json-update "{test: 'no quotes for field name, and using single quotes here'}")
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment