-
-
Notifications
You must be signed in to change notification settings - Fork 83
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
61 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,61 @@ | ||
(ns portal.http-socket-server | ||
(:require [clojure.java.io :as io] | ||
[clojure.string :as string]) | ||
(:import [java.net ServerSocket])) | ||
|
||
(defn handler [request] | ||
{:status 200 | ||
:headers {"Content-Type" "application/json"} | ||
:body "{\"hello\": \"world\"}"}) | ||
|
||
(defn parse-request [in] | ||
(let [[req-line & headers] | ||
(loop [headers []] | ||
(let [line (.readLine in)] | ||
(if (string/blank? line) | ||
headers | ||
(recur (conj headers line))))) | ||
[method path] (string/split req-line #" ")] | ||
{:method method | ||
:uri path | ||
:headers (->> headers | ||
(map #(string/split % #": ")) | ||
(into {}))})) | ||
|
||
(def messages | ||
{200 "OK" | ||
404 "Not Found"}) | ||
|
||
(defn format-response [response] | ||
(let [{:keys [status body headers]} response | ||
headers (assoc headers "Content-Length" (count (.getBytes body)))] | ||
(str "HTTP/1.1 " status " " (get messages status) "\r\n" | ||
(string/join | ||
(map (fn [[k v]] (str k ": " v "\r\n")) headers)) | ||
"\r\n" | ||
body))) | ||
|
||
(defn start-worker-thread [client-socket request-handler] | ||
(.start | ||
(Thread. | ||
(fn [] | ||
(with-open [in (io/reader (.getInputStream client-socket)) | ||
out (io/writer (.getOutputStream client-socket))] | ||
(let [request (parse-request in) | ||
response (request-handler request) | ||
{:keys [status body]} response] | ||
(.write out (format-response response))) | ||
(.flush out)))))) | ||
|
||
(defn start [] | ||
(let [server-socket (ServerSocket. 4444) | ||
port (.getLocalPort server-socket) | ||
_ (println "Serv: Awaiting connection on port " port)] | ||
(while true | ||
(let [client-socket (.accept server-socket)] | ||
(start-worker-thread client-socket #'handler))))) | ||
|
||
(defn stop []) | ||
|
||
(defn -main [] | ||
(start)) |