8

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?

Anton Harald
  • 5,772
  • 4
  • 27
  • 61

3 Answers3

12

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))
Dave Liepmann
  • 1,555
  • 1
  • 18
  • 22
Piotrek Bzdyl
  • 12,965
  • 1
  • 31
  • 49
4

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

(defn handler [request]
  (let [body (slurp (:body request))]))
kazuwal
  • 1,071
  • 17
  • 25
  • Please don't post only code as answer, but also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes. – Mark Rotteveel Jul 30 '21 at 08:23
  • @MarkRotteveel you are correct. Updated my response :) – kazuwal Jul 30 '21 at 11:55
0

The :body of ring request must be an instance of java.io.InputStream. So you can use reader + slurp to get a string out.

(defn is->str [is]
  (let [rdr (clojure.java.io/reader is)]
    (slurp rdr)))

Usage: (is->str (:body request))

Ming
  • 4,110
  • 1
  • 29
  • 33