Created
June 12, 2010 09:27
-
-
Save juergenhoetzel/435597 to your computer and use it in GitHub Desktop.
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
(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")) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks again for this. It gave me some good ideas for the refactoring.
:f