Skip to content

Instantly share code, notes, and snippets.

@juergenhoetzel
Created June 12, 2010 09:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save juergenhoetzel/435597 to your computer and use it in GitHub Desktop.
Save juergenhoetzel/435597 to your computer and use it in GitHub Desktop.
(ns joy.web
(:import (com.sun.net.httpserver HttpHandler HttpExchange HttpServer)
(java.net InetSocketAddress HttpURLConnection)
(java.io IOException FilterOutputStream)
(java.util Arrays)))
(defn default-handler [txt]
(proxy [HttpHandler] []
(handle [exchange]
(.sendResponseHeaders exchange HttpURLConnection/HTTP_OK (.length txt))
(doto (.getResponseBody exchange)
(.write (.getBytes txt))
(.close)))))
(defn new-server [port path handler]
(doto (HttpServer/create (InetSocketAddress. port) 0)
(.createContext path handler)
(.setExecutor nil)
(.start)))
(defn change-message
"Convenience method to change a proxy's output message"
([p txt] (change-message p identity txt))
([p fltr txt]
(update-proxy p
{"handle"
(fn [this exchange]
(let [txt (fltr txt)
b (.getBytes txt)]
(.sendResponseHeaders exchange
HttpURLConnection/HTTP_OK
(count b))
(doto (.getResponseBody exchange)
(.write b)
(.close))))})))
(defn aloha-filter [#^String s]
(.replaceAll s "Hello" "Aloha"))
@fogus
Copy link

fogus commented Jul 12, 2010

Thanks again for this. It gave me some good ideas for the refactoring.
:f

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment