Skip to content

Instantly share code, notes, and snippets.

@austinhaas
Created September 4, 2012 23:53
Show Gist options
  • Save austinhaas/3628228 to your computer and use it in GitHub Desktop.
Save austinhaas/3628228 to your computer and use it in GitHub Desktop.
Using virtual hosts with Clojure and Jetty
;;; This is my first pass at setting up virtual hosts; it works, but there is room for improvement.
;;; dependencies
;;[ring "1.1.5"]
;;[javax.servlet/servlet-api "2.5"]
;;[org.eclipse.jetty/jetty-server "7.6.1.v20120215"]
;;[org.eclipse.jetty/jetty-servlet "7.6.1.v20120215"]
(ns app.core
(:require [ring.util.servlet :refer (servlet)]
[ring.adapter.jetty :refer (run-jetty)])
(:import [org.eclipse.jetty.servlet ServletContextHandler ServletHolder]
org.eclipse.jetty.server.handler.ContextHandlerCollection))
(defn add-virtual-hosts [server host-specs]
(.stop server)
(let [contexts (for [[host handler] host-specs]
(doto (ServletContextHandler. ServletContextHandler/SESSIONS)
(.setContextPath "/")
(.setVirtualHosts (into-array [host]))
(.addServlet (ServletHolder. (servlet handler)) "/")))
context-coll (ContextHandlerCollection.)]
(.setHandlers context-coll (into-array contexts))
(.setHandler server context-coll))
(.start server))
(def server (run-jetty nil {:port 8080 :join? false}))
(add-virtual-hosts server [["api.myproject.com" my-api-handler]
["myproject.com" my-browser-client-handler]])
@johnbendi
Copy link

Is this still how you set up virtual hosts today or have you discovered something better with jetty or other servers for clojure?

@johnbendi
Copy link

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