Search code examples
clojurering

clojure ring-http is not giving expected response


I'm writing a http app using ring clojure using lein.

My project.clj is -

(defproject ring-app "0.1.0-SNAPSHOT"
  :description "FIXME: write description"
  :url "http://example.com/FIXME"
  :license {:name "EPL-2.0 OR GPL-2.0-or-later WITH Classpath-exception-2.0"
            :url "https://www.eclipse.org/legal/epl-2.0/"}
  :dependencies [[org.clojure/clojure "1.11.1"]
                 [ring "1.10.0"]]
  :repl-options {:init-ns ring-app.core}
  :main ring-app.core)

My handler is -

(ns ring-app.core
  (:require [ring.adapter.jetty :as jetty]))

(defn foo
  "I don't do a whole lot."
  [x]
  (println x "Hello, World!"))


(defn handler [request-map]
  (println "got a request to process ...")
  {:status 200
   :headers {"Content-Type" "text/html"}}
   :body (str "<html><body> Your IP is : " (:remote-addr request-map) "</body></html>"))


(defn -main []
  (println "starting handler...")
  (jetty/run-jetty handler  {:port 3000 :join? false}))

When I do curl I get 200 response but not body and headers as set in my handler

curl -v http://localhost:3000
*   Trying 127.0.0.1:3000...
* Connected to localhost (127.0.0.1) port 3000 (#0)
> GET / HTTP/1.1
> Host: localhost:3000
> User-Agent: curl/7.85.0
> Accept: */*
>
* Mark bundle as not supporting multiuse
< HTTP/1.1 200 OK
< Date: Fri, 07 Apr 2023 21:10:29 GMT
< Content-Length: 0
< Server: Jetty(9.4.51.v20230217)
<
* Connection #0 to host localhost left intact

My serverlog is printing the (println "got a request to process...") but not the response I'm expecting.

clojure ring server log Any idea why I'm not getting body and response?

The project is on github here


Solution

  • Your handler function has the :body key and its value outside the response hash map you are trying to create.

    You want this:

    (defn handler [request-map]
      (println "got a request to process ...")
      {:status 200
       :headers {"Content-Type" "text/html"}
       :body (str "<html><body> Your IP is : " (:remote-addr request-map) "</body></html>")})
    

    See where I've moved that closing } to?