Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
tiny http server via java sockets in clojure
#!/usr/bin/env clojure
(import ( ServerSocket))
(require '[clojure.string :as string] '[ :as io])
(letfn [(req-line+headers [in]
(binding [*in* in]
(loop [headers []]
(let [line (read-line)]
(if (string/blank? line)
(recur (conj headers line)))))))
(hiccup [el]
(and (coll? el)
(keyword? (first el))) (let [[tag attrs & els] el
kvs (when (map? attrs)
(for [[k v] attrs]
(format "%s=%s" (name k) (str v))))]
(concat ["<" (string/join " " (cons (name tag) kvs)) ">"]
(map hiccup (if (map? attrs)
(cons attrs els)))
["</" (name tag) ">"]))
(coll? el) (map hiccup el)
:else [el])))]
(with-open [server-socket (ServerSocket. 8081)
client-socket (.accept server-socket)]
(let [out (io/writer (.getOutputStream client-socket))
in (io/reader (.getInputStream client-socket))
[req-line & headers] (req-line+headers in)
[_ _ path _] (re-find #"([^\s]+)\s([^\s]+)\s([^\s]+)" req-line)
f (io/file (format "./%s" path))
found? (.exists f)
status (if found? 200 404)
body (cond
(not found?) ""
(.isFile f) (slurp f)
(.isDirectory f) (format "<!DOCTYPE html>\n%s"
(hiccup [:html {}
[:head {}
[:title {} path]]
[:body {}
[:h1 {} path]
[:tt {}
[:pre {}
(for [i (.list f)]
[:div [:a {:href (format "\"%s\"" i)} i]])]]]])))]
(.write out (format "HTTP/1.1 %s OK\r\nContent-Length: %s\r\n\r\n%s"
(count (.getBytes body))
(binding [*out* out]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.