6

我正在努力从 put 中返回 JSON!要求:

我的代码如下所示:

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

我只想将传递给 put 请求的任何内容作为 JSON 返回,直到我了解发生了什么。

但是,如果我提出 put 请求,我会得到以下响应:

HTTP/1.1 201 创建

日期:2014 年 5 月 18 日星期日 15:35:32 GMT

内容类型:文本/纯文本

内容长度:0

服务器:码头(7.6.8.v20121106)

我的 GET 请求返回 JSON,所以我不明白为什么 PUT 请求不是/

4

1 回答 1

6

That is because a successfull PUT request does not return a http 200 status code (at least according to liberator), it returns a http 201 status code, as you can see from the response. Liberator handle http status code each in a different handler. In order to achieve what you want, you have 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 declare none on :handle-created, it defaults to an empty string with a text/plain content-type.

Edit:

In order to understand more, you have to see the decision graph. In there, you can see that after handling put! it goes to decision handling new?, if it's true go to handle-created if false, go to respond-with-entity? and so on.

于 2014-05-18T17:07:38.853 回答