요청 및 응답 처리
들어오는 요청 데이터를 구문 분석하고 JSON과 HTML을 포함한 적절한 HTTP 응답을 구성하는 방법을 숙달합니다.
요청 및 응답 처리은(는) CoddyKit의 무료 Clojure Functional Programming & JVM Backend Development 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Clojure Functional Programming & JVM Backend Development 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Clojure Functional Programming & JVM Backend Development 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Handling Requests & Responses
In web development, your application constantly handles incoming requests from clients and sends back appropriate responses. This lesson teaches you how to read data from a client's request and construct different types of responses, like HTML and JSON, using Clojure's Ring.
Understanding the Ring Request Map
When a request hits your Clojure application, Ring transforms it into a standard Clojure map, often called the request map. This map contains all details about the incoming request, such as:
:uri: The path of the request (e.g.,"/users"):request-method: The HTTP method (e.g.,:get,:post):headers: A map of all HTTP headers:query-params: A map of URL query parameters:body: The request body, if any
Accessing Query & Form Parameters
Clients often send data via URL query parameters (e.g., /search?q=clojure) or HTML form parameters. Ring provides these parsed in the :query-params and :form-params keys of the request map, respectively. You can access them like any other map entry.
Code: Query Parameter Demo
Try running this example to see how to extract a query parameter. We'll simulate a request map for a handler function.
(ns coddykit.core
(:require [ring.util.response :refer [response]]))
(defn greet-handler [request]
(let [name (get-in request [:query-params "name"] "Guest")]
(response (str "Hello, " name "!"))))
(defn -main []
(let [mock-request {:query-params {"name" "Coddy"}}]
(println "Simulating request with name 'Coddy':")
(let [res (greet-handler mock-request)]
(println "Status:" (:status res))
(println "Body:" (:body res))))
(let [mock-request-no-name {:query-params {}}]
(println "\nSimulating request with no name:")
(let [res (greet-handler mock-request-no-name)]
(println "Status:" (:status res))
(println "Body:" (:body res))))Reading the Request Body
When clients send data in the request body (e.g., for POST or PUT requests), this data is available in the :body key of the request map. For common formats like JSON, you'll typically use a Ring middleware to parse the raw body into a Clojure map automatically. Without middleware, :body contains an InputStream.
Building Your Response Map
After processing a request, your handler function must return a response map. This map tells Ring how to construct the HTTP response sent back to the client. A minimal response map needs:
:status: The HTTP status code (e.g.,200for OK,404for Not Found):headers: A map of HTTP headers (e.g.,{"Content-Type" "text/html"}):body: The actual content to send back (e.g., HTML string, JSON string)
Responding with HTML
To send an HTML page, your response map's :body should be an HTML string, and the "Content-Type" header must be set to "text/html". Ring's response helper function is a great starting point, and header helps add headers.
Code: HTML Response Demo
Here's how to create a simple handler that responds with an HTML page. Note the use of header to set the correct content type.
(ns coddykit.core
(:require [ring.util.response :refer [response header]]))
(defn html-page-handler [request]
(-> (response "<h1>Welcome to CoddyKit!</h1><p>This is an HTML page.</p>")
(header "Content-Type" "text/html")))
(defn -main []
(let [mock-request {}]
(println "Simulating request for HTML page:")
(let [res (html-page-handler mock-request)]
(println "Status:" (:status res))
(println "Headers:" (:headers res))
(println "Body:" (:body res)))))Responding with JSON
For API endpoints, you'll often send data back as JSON. This requires setting the "Content-Type" header to "application/json" and ensuring your :body contains a valid JSON string. You'll typically use a library like clojure.data.json or cheshire to convert Clojure data structures into JSON strings.
Code: JSON Response Demo
This example shows how to send a JSON response. We use clojure.data.json to convert a Clojure map to a JSON string.
(ns coddykit.core
(:require [ring.util.response :refer [response header]]
[clojure.data.json :as json]))
(defn json-data-handler [request]
(let [data {:status "success" :message "Data received!"}]
(-> (response (json/write-str data))
(header "Content-Type" "application/json"))))
(defn -main []
(let [mock-request {}]
(println "Simulating request for JSON data:")
(let [res (json-data-handler mock-request)]
(println "Status:" (:status res))
(println "Headers:" (:headers res))
(println "Body:" (:body res)))))Quick Check: Response Structure
You're building an API and need to send a successful response with a JSON object {"message": "Item created"}. Which of the following correctly represents the Ring response map?
Recap: Requests & Responses
You've learned how to handle the core of web interactions in Clojure! We covered:
- The structure of the Ring request map and how to access its data.
- Extracting query and form parameters from requests.
- Understanding how request bodies (like JSON) are handled.
- Constructing Ring response maps with
:status,:headers, and:body. - Sending back both HTML and JSON content by setting the appropriate
Content-Typeheader.
These are fundamental skills for building any web application with Ring and Compojure!
자주 묻는 질문
“요청 및 응답 처리” 강의는 무료인가요?
네 — “요청 및 응답 처리” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Clojure Functional Programming & JVM Backend Development 강의 전체를 잠금 해제할 수 있습니다. Clojure Functional Programming & JVM Backend Development 강의에는 총 4개의 강의가 포함되어 있습니다.
“요청 및 응답 처리”에서 뭘 배우나요?
들어오는 요청 데이터를 구문 분석하고 JSON과 HTML을 포함한 적절한 HTTP 응답을 구성하는 방법을 숙달합니다. 브라우저에서 직접 실행하는 실습 코드로 Clojure Functional Programming & JVM Backend Development을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Clojure Functional Programming & JVM Backend Development을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Clojure Functional Programming & JVM Backend Development은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.
“요청 및 응답 처리” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Clojure Functional Programming & JVM Backend Development 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Clojure Functional Programming & JVM Backend Development 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.