Skip to content

Instantly share code, notes, and snippets.

@ikitommi
Created January 17, 2018 06:17
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save ikitommi/036a5e6a24691f23a419404ff4595473 to your computer and use it in GitHub Desktop.
compojure-api with text/plain
lein try metosin/compojure-api "2.0.0-alpha17" org.immutant/immutant
(require '[muuntaja.core :as m])
(require '[compojure.api.sweet :refer :all])
(require '[ring.util.http-response :refer :all])
(require '[immutant.web])
(import '(java.io InputStreamReader ByteArrayInputStream InputStream))

(def text-plain-adapter
  {:decoder [(fn decoder [_]
               (fn [x ^String charset]
                 (if (string? x) x (slurp (InputStreamReader. ^InputStream x charset)))))]
   :encoder [(fn encoder [_]
               (fn [data ^String charset] (ByteArrayInputStream. (.getBytes data charset))))]})

(def muuntaja
  (m/create
    (assoc-in m/default-options [:formats "text/plain"] text-plain-adapter)))

(def app
  (api
    {:swagger {:ui "/swagger-ui"
               :spec "/swagger.json"
               :data {:info {:version 1
                             :title "api"}}}
     :formats muuntaja}

    (context "/v1/a" []
      (POST "/b" []
        :body [body String]
        (ok {:msg (str "ok" body)})))))

(immutant.web/run #'app {:port 3000})
;➜  ~ curl --verbose -H "Content-Type: text/plain" -d 'abcde' http://localhost:3000/v1/a/b
;
;*   Trying ::1...
;* TCP_NODELAY set
;* Connection failed
;* connect to ::1 port 3000 failed: Connection refused
;*   Trying 127.0.0.1...
;* TCP_NODELAY set
;* Connected to localhost (127.0.0.1) port 3000 (#0)
;> POST /v1/a/b HTTP/1.1
;> Host: localhost:3000
;> User-Agent: curl/7.54.0
;> Accept: */*
;> Content-Type: text/plain
;> Content-Length: 5
;>
;* upload completely sent off: 5 out of 5 bytes
;< HTTP/1.1 200 OK
;< Connection: keep-alive
;< Server: undertow
;< Content-Type: application/json; charset=utf-8
;< Content-Length: 17
;< Date: Wed, 17 Jan 2018 06:15:32 GMT
;<
;* Connection #0 to host localhost left intact
{"msg":"okabcde"}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment