Last active
April 7, 2024 03:02
-
-
Save bowmanb/8560704 to your computer and use it in GitHub Desktop.
An example Jetty component using Stuart Sierra's component Clojure library.
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 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})) |
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 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")) |
Definitely. Thanks @stig.
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)
Updated per @the-kenny comment. Found a little more info here.
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
Perhaps return
(dissoc component :server)
rather thancomponent
from thestop
function?