Skip to content

Instantly share code, notes, and snippets.

@ToddG
Created August 6, 2010 18:08
Show Gist options
  • Save ToddG/511710 to your computer and use it in GitHub Desktop.
Save ToddG/511710 to your computer and use it in GitHub Desktop.
(ns web01.core
(:import
java.util.Map
java.util.HashMap
[java.io File InputStream]
[clojure.lang IDeref IFn ISeq])
(:use
compojure.core,
ring.adapter.jetty
clojure.contrib.json.read
clojure.contrib.json.write )
(:require
[compojure.response :as response]
[compojure.route :as route] ))
;---------------------------------------
; for testing, switch between text and json
;---------------------------------------
(def json-header {"Content-Type" "application/json"})
(def text-header {"Content-Type" "text/html"} )
; for debugging
(def header text-header)
;---------------------------------------
; define a java.util.HashMap
;---------------------------------------
(def hashmap
(let [
body (HashMap.)
hmap (HashMap.)]
(doto body
(.put "a" 1)
(.put "b" 2)
(.put "c" 3))
(doto hmap
(.put :body body))
hmap))
;---------------------------------------
; TODO: define a java Array
;---------------------------------------
(def an-array (to-array ["one" "two" "three"]))
;---------------------------------------
; overrides
;---------------------------------------
(defmethod response/render String [_ html]
{:status 200 :headers header :body (json-str html)})
(defmethod response/render ISeq [_ coll]
{:status 200, :headers header, :body (json-str coll)})
(defmethod response/render Map [_ m]
(merge
{:status 200, :headers header, :body ""}
m
{:body (json-str (:body m ""))}))
; added method to process 'an-array', which is passed as a java.lang.Object
(defmethod response/render Object [_ o]
{:status 200, :headers header, :body (json-str o)})
(defroutes main-routes
; handled by the 'response/render String method
(GET "/jsonarray" [] (json-str [1,2,3]))
; clojure *and* java maps need to be wrapped in a :body, as the 'render Map' method is preferred in response/render
; multi-method...and I cannot seem to override this
(GET "/map" [] {:body {"a" 1, "b" 2, "c", 3}})
(GET "/hashmap" [] hashmap)
; array is passed as a java.lang.Object
(GET "/array" [] an-array)
; I'm not sure why the vector isn't recognized by the 'response/render ISeq' method...
(GET "/vector" [] [1,2,3])
; handled by the 'response/render ISeq' method
(GET "/list" [] (list 1 2 3))
; 404 the request
(GET "/404" [] {:status 404 :headers header :body {"data" "nothing"}})
(route/not-found "<h1>Page not found</h1>"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment