ring: read body of a http request as string

后端 未结 2 1673
情深已故
情深已故 2021-01-19 00:50

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:

相关标签:
2条回答
  • 2021-01-19 01:05

    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))
    
    0 讨论(0)
  • 2021-01-19 01:05

    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))

    0 讨论(0)
提交回复
热议问题