exupero's blog
RSSApps

Babashka script to serve stdin

Here's a small Babashka script that reads stdin, serves it, opens a browser tab to it, then shuts the server down:

(require '[clojure.java.browse :as browse]
         '[org.httpkit.server :as server])

(let [port (with-open [sock (java.net.ServerSocket. 0)]
             (.getLocalPort sock))
      html (slurp System/in)
      done? (promise)]
  (server/run-server
    (fn [_]
      (future
        (Thread/sleep 100)
        (deliver done? true))
      {:status 200 :body html})
    {:port port})
  (browse/browse-url (str "http://localhost:" port))
  @done?
  nil)

I typically use this at the end of a shell pipeline that generates HTML, such as one that turns data into a Vega specification and embeds it in some boilerplate HTML. Then I can tweak the data transformation or plot parameters at the command line and immediately have the result in a browser.