Skip to content

Instantly share code, notes, and snippets.

@bowmanb
Last active April 7, 2024 03:02
Show Gist options
  • Save bowmanb/8560704 to your computer and use it in GitHub Desktop.
Save bowmanb/8560704 to your computer and use it in GitHub Desktop.
An example Jetty component using Stuart Sierra's component Clojure library.
(ns my-project.http-server
(:require [compojure.core :as compojure]
[com.stuartsierra.component :as component]
[my-project.my-resource :as my-resource]
[ring.adapter.jetty :as jetty]))
(compojure/defroutes app
my-resource/handler)
(defrecord HTTPServer [port server]
component/Lifecycle
(start [component]
(println ";; Starting HTTP server")
(let [server (jetty/run-jetty app {:port port :join? false})]
(assoc component :server server)))
(stop [component]
(println ";; Stopping HTTP server")
(.stop server)
(assoc component :server nil)))
(defn new-http-server
[port]
(map->HTTPServer {:port port}))
(ns my-project.http-server-test
(:require [my-project.http-server :refer [new-http-server]]
[clojure.test :refer [deftest is]]
[com.stuartsierra.component :as component]))
(def http-server (new-http-server 8080))
(deftest http-server-lifecycle
(alter-var-root #'http-server component/start)
(is (:server http-server) "HTTP server has been added to component")
(is (.isStarted (:server http-server)) "HTTP server starts")
(alter-var-root #'http-server component/stop)
(is (nil? (:server http-server)) "HTTP server instance is removed from component"))
@the-kenny
Copy link

This won't work - it will not return a HTTPServer anymore but a plain clojure map (as you dissoc a required key from a record)

@bowmanb
Copy link
Author

bowmanb commented Dec 14, 2015

Updated per @the-kenny comment. Found a little more info here.

@danielsz
Copy link

danielsz commented May 3, 2016

server does not need be a base field of HTTPServer. Then you can dissoc it from the component on stop.

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