Clojure Ring HTTP服务未返回预期响应问题求助
问题排查:Ring HTTP应用仅返回200状态码无响应头和响应体
问题场景
使用Leiningen构建Clojure Ring HTTP应用,项目配置文件project.clj内容:
(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)
处理器代码ring-app.core内容:
(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}))
执行curl -v http://localhost:3000请求时,仅返回200状态码,无法获取代码中设置的响应头和响应体;服务器日志能打印请求处理提示,但返回结果不符合预期。
问题原因
核心错误是handler函数返回的响应Map存在语法错误::body键被写在了Map的闭合括号}外面,导致实际返回的Map仅包含:status和:headers两个键,:body成为了独立的无效表达式。Ring要求响应必须是包含:status、:headers、:body的完整Map,缺少:body或结构错误时,就会出现仅返回状态码的情况。
修复方案
将:body键移至响应Map内部,修正后的handler函数代码:
(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>")})
修复后重启应用,再次执行curl -v http://localhost:3000,即可获取包含正确响应头和客户端IP内容的响应体。
内容的提问来源于stack exchange,提问作者user51
相关产品推荐
相关产品推荐

