Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ring: read body of a http request as string

Tags:

clojure

ring

When handling a http request inside a ring server, the body of the request-data is stored in the request-hashmap in the key :body. For instance as followed:

#object[org.eclipse.jetty.server.HttpInputOverHTTP 0x2d88a9aa "HttpInputOverHTTP@2d88a9aa"] 

In case, I'm just interested in the raw text, how an I read out this object?

like image 213
Anton Harald Avatar asked May 23 '16 17:05

Anton Harald


Video Answer


2 Answers

You can use ring.util.request/body-string to get the request body as a String.

(body-string request) 

You need to remember that InputStream can be read only once so you might prefer replace the original :body with the read String instead so you can later access it again:

(defn wrap-body-string [handler]
  (fn [request]
    (let [body-str (ring.util.request/body-string request)]
      (handler (assoc request :body (java.io.StringReader. body-str))))))

And add your middleware to wrap your handler:

(def app
  (wrap-body-string handler))
like image 142
Piotrek Bzdyl Avatar answered Oct 14 '22 18:10

Piotrek Bzdyl


As suggested by user1338062 you can simply call slurp on the body of the request.

(defn handler [request] (let [body (slurp (:body request))]))

like image 24
insudo Avatar answered Oct 14 '22 18:10

insudo