如何在clojure/ring中发起http呼叫?

我的网络客户端(写在cljs)连接到后端(编写在clj)需要进行一些第三方API调用。它必须在服务器上完成,然后结果应该以特定方式进行转换并发送回客户端。如何在clojure/ring中发起http呼叫?

这里是我的网址

(defn get-orders [req] 

(let [{:keys [sig uri]} (api-signature :get-orders)]

(client/get uri

{:async? true}

(fn [response] {:body "something"})

(fn [exception] {:body "error"}))))

,而不是返回{:body "something"}的一个处理程序,它返回以下错误:

No implementation of method: :render of protocol: #'compojure.response/Renderable found for class: org.apache.http.impl.nio.client.FutureWrapper 

我在做什么错?

回答:

当您指定{:async? true}时,clj-http.client/get将返回a future这是您得到的错误消息中的FutureWrapper

所以,如果你不需要异步,不要使用它。这是一个同步环处理程序的例子,它调用第三方url并返回返回的响应。

(defn handler [request] 

(response {:result (client/get "http://example.com")}))

如果您确实需要异步,请使用异步版本的环处理程序。

(defn handler [request respond raise] 

(client/get "http://example.com"

{:async? true}

(fn [response] (respond {:body "something"}))

(fn [exception] (raise {:body "error"}))))

不要忘记配置web服务器适配器以使用异步处理程序。例如,对于码头,设置:async?标志true像这样

(jetty/run-jetty app {:port 4000 :async? true :join? false}) 

如果要同时调用多个第三方URL和一次web客户端返回,使用promise帮助

(defn handler [request] 

(let [result1 (promise)

result2 (promise)]

(client/get "http://example.com/"

{:async? true}

(fn [response] (deliver result1 {:success true :body "something"}))

(fn [exception] (deliver result1 {:success false :body "error"})))

(client/get "http://example.com/"

{:async? true}

(fn [response] (deliver result2 {:success true :body "something"}))

(fn [exception] (deliver result2 {:success false :body "error"})))

(cond

(and (:success @result1)

(:success @result2))

(response {:result1 (:body @result1)

:result2 (:body @result2)})

(not (:success @result1))

(throw (ex-info "fail1" (:body @result1)))

(not (:success @result2))

(throw (ex-info "fail2" (:body @result2))))))

以上是 如何在clojure/ring中发起http呼叫? 的全部内容, 来源链接: utcz.com/qa/258731.html

回到顶部