gpt4 book ai didi

clojure liberator - 从 put 请求返回 json

转载 作者:行者123 更新时间:2023-12-02 10:43:30 26 4
gpt4 key购买 nike

我正在努力从 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 Created

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

Content-Type: text/plain

Content-Length: 0

Server: Jetty(7.6.8.v20121106)

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

最佳答案

这是因为成功的 PUT 请求不会返回 http 200 状态代码(至少根据 liberator 的说法),它会返回 http 201 状态代码,正如您从响应中看到的那样。 Liberator 在不同的处理程序中分别处理 http 状态代码。为了实现你想要的,你必须这样做:

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

由于您在 :handle-created 上没有声明任何内容,因此它默认为具有文本/纯内容类型的空字符串。

编辑:

为了了解更多,您必须查看 decision graph 。在那里,您可以看到在处理 put! 后,它会进入决策处理 new?,如果为 true,则进入 handle-created 如果为 false ,转到 respond-with-entity? 等等。

关于clojure liberator - 从 put 请求返回 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23723785/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com