clojure - 如何从post返回json数据! Clojure 解放者中的处理程序?

标签 clojure liberator

如何使用 Clojure Liberator 返回 json 数据?此代码不起作用:

(defresource poster []
         :allowed-methods [:post :options]
         :available-media-types ["application/json"]
         :post!      (fn [ctx] (println "posting..."))
         :handle-created (fn [ctx] {:created "ok"}))

是否应该在发布后调用handle-created?

最佳答案

:post! 键关联的函数不是处理函数。 Liberator 文档将其称为操作函数。

Action functions The keys :post!, :put! and :delete! provide points that are suited well to enact side effects. While they are evaluated like decision functions, the boolean value has no effect and the next decision step is constant. The context update works exactly like for decision functions.

因此您无法直接从与 :post! 关联的函数生成 http 响应。

:post! 键关联的函数可以返回一些内容,并且该内容将被合并到上下文中。

The context update works exactly like for decision functions.

然后处理函数可以稍后从上下文中提取该内容并使用它来形成 http 响应。与这些键关联的任何一个处理函数都可能随后执行::handle-ok:handle-created:handle-no-内容:handle-see-other:handle-multiple-representations

这个decision graph确定将执行哪个处理程序。

最好只使用指向新创建的资源的位置 header 进行响应,而不使用正文,但这里是一个使用 JSON 正文和 201 状态创建响应的示例。

(POST "/foo" [] (resource :allowed-methods [:post]
                           :available-media-types ["application/json"]
                           :handle-created {:created "ok"}))

尝试一下:

curl -X POST "localhost/foo" 
{"created":"ok"}

您可以在 project.clj 中看到 Liberator 使用哪个 JSON 库文件。如果你想自己生成 JSON 字符串,你可以这样做:

:handle-created (fn [ctx] (liberator.representation/ring-response 
                          {:status 201 :body "{created:\"ok\"}"}))

提到here

关于clojure - 如何从post返回json数据! Clojure 解放者中的处理程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28107448/

相关文章:

Clojure 原子将向量转换为列表?

clojure - Clojure 列表中的惯用和懒惰最终为真

clojure - 如何在 Clojure 中使用 Liberator 重定向 get 方法?

clojure - 在 Liberator Clojure 中发布未返回 200 OK

java - JOD Converter to pdf API 不认识 docx?

java - 从 Java 向 Clojure 传递参数

clojure - 惰性序列最小-最大查找器 stackoverflow 问题

clojure - 使用 Liberator 从 POST 中获取包含关键字的 clojure 映射

rest - 我使用 clojure 创建 REST API。如何自动生成REST文档?