Skip to content

Instantly share code, notes, and snippets.

@shenfeng
Last active January 23, 2024 19:23
Show Gist options
  • Save shenfeng/4700178 to your computer and use it in GitHub Desktop.
Save shenfeng/4700178 to your computer and use it in GitHub Desktop.
High performance HTTP proxy with http-kit
(ns org.httpkit.proxy-test
(:use [org.httpkit.server :only [run-server async-response]]
[org.httpkit.client :only [request]]))
(defn- proxy-opts [req]
{:url (str "http://192.168.1.101:9090" (:uri req)
(if-let [q (:query-string req)]
(str "?" q)
""))
:timeout 30000 ;ms
:method (:request-method req)
:headers (assoc (:headers req)
"X-Forwarded-For" (:remote-addr req))
:body (:body req)})
(defn handler [req]
(async-response respond
(request (proxy-opts req)
(fn [{:keys [status headers body error]}]
(if error
(respond {:status 503
:headers {"Content-Type" "text/plain"}
:body (str "Cannot access backend\n" error)})
(respond {:status status
:headers (zipmap (map name (keys headers)) (vals headers))
:body body}))))))
;; ab -n 500000 -c 100 -k http://127.0.0.1:8080/ => 25k requests/second on my PC
(defn -main [& args]
(run-server handler {:port 8080})
(println "proxy server started at 0.0.0.0@8080"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment