Clojure liberator - return json from put request

I'm struggling to get JSON back from the spot! request:

My code is as follows:

(defn body-as-string [ctx] (if-let [body (get-in ctx [:request :body])] (condp instance? body java.lang.String body (slurp (io/reader body))))) (defn orbit-world [dimensions ctx] (let [in (json/parse-string (body-as-string ctx))] (json/generate-string in))) (defn init-world [params] (let [dimensions (Integer/parseInt params) world (vec (repeat dimensions (vec (take dimensions (repeatedly #(rand-int 2))))))] (json/generate-string world))) (defresource world [dimensions] :allowed-methods [:get :put] :available-media-types ["application/json"] :available-charsets ["utf-8"] :handle-ok (fn [_] (init-world dimensions)) :put! (fn [ctx] (orbit-world dimensions ctx))) 

I just want to return everything that is transferred to the request request as JSON until I understand what is happening.

But if I make a request request, I get the following response:

HTTP / 1.1 201 Created

Date: Sun, May 18, 2014 15:35:32 GMT

Content-Type: text / plain

Content-Length: 0

Server: jetty (7.6.8.v20121106)

My GET request returns JSON, so I do not understand why the PUT request is not /

+6
source share
1 answer

This is because a successful PUT request does not return an http 200 status code (at least according to the liberator), it returns an http 201 status code, as you can see from the answer. Liberator processes the http status code each in a different handler. To achieve what you want, you need to do:

 (defresource world [dimensions] :allowed-methods [:get :put] :available-media-types ["application/json"] :available-charsets ["utf-8"] :handle-ok (fn [_] (init-world dimensions)) :put! (fn [ctx] (orbit-world dimensions ctx)) :handle-created (fn [_] (init-world dimensions))) ; Basically just a handler like any other. 

Since you are not declaring any of them: handle-created, the default is to use an empty string with a text / regular content type.

Edit:

To understand more, you should see a graph. There you can see that after processing put! Does he move on to handling new? solutions new? if true go to handle-created , if false go to respond-with-entity? etc.

+6
source

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


All Articles