Skip to content

Add content type negotiation for text types #3

@vincentjames501

Description

@vincentjames501

Most other clj based http clients (clj-http, http-kit, hato, etc) either default to returning a String for :body or attempt to negotiate the content type. When they make a request to something like GET https://apple.com or GET https://google.com, the :body is returned as text instead of an InputStream. It would be nice when a response's content-type is text/plain, text/html, text/css, etc for the body to be automatically converted to a string similar to other content negotiations. I'd argue any content type that is text/* should be auto coerced to a string w/ proper encoding. Thoughts? I was actually surprised muuntaja doesn't do this automatically though we could add additional formats like so:

(defn decoder [_]
  (reify
    mf/Decode
    (decode [_ data charset]
      (slurp data :encoding charset))))

(defn encoder [_]
  (reify
    mf/EncodeToBytes
    (encode-to-bytes [_ data charset]
      (.getBytes ^String data ^String charset))
    mf/EncodeToOutputStream
    (encode-to-output-stream [_ data charset]
      (fn [^OutputStream output-stream]
        (.write output-stream (.getBytes
                                ^String data
                                ^String charset))))))

(def text-format
  (mf/map->Format
    {:name    "text/plain"
     :decoder [decoder]
     :encoder [encoder]}))

(def muuntaja (m/create (-> m/default-options
                            (update :formats assoc "text/plain" text-format)
                            (assoc :return :output-stream))))

It would be nice to support :as a bit better as well. For example adding support for :byte-array, :text/:string, :input-stream etc can be pretty nice where the default if content-negotiation couldn't be done automatically be a string?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions