luminus-framework / ring-undertow-adapter

Ring Undertow adapter
MIT License
44 stars 12 forks source link

ring-undertow-adapter

ring-undertow-adapter is a Ring server built with Undertow.

Installation

Clojars Project

Usage

HTTP Handler

HTTP handler returns an Undertow server instance. To stop call (.stop <handler instance>). The handler is initialized using a map with the following keys:

(require '[ring.adapter.undertow :refer [run-undertow]])

(defn handler [req]
  {:status 200
   :body "Hello world"})

(run-undertow handler {:port 8080})

WebSocket Handler

A WebSocket handler is created using a Ring handler function that returns a map containing a :undertow/websocket containing the configuration map:

(require '[ring.adapter.undertow.websocket :as ws])

(fn [request]
  {:undertow/websocket 
   {:on-open (fn [{:keys [channel]}] (println "WS open!"))
    :on-message (fn [{:keys [channel data]}] (ws/send "message received" channel))
    :on-close-message (fn [{:keys [channel message]}] (println "WS closeed!"))}})

If headers are provided in the map returned from the handler function they are included in the response to the WebSocket upgrade request. Handlers relevant to the WebSocket handshake (eg Connection) will be overwritten so that the WebSocket handshake completes correctly:

(defn- websocket-handler-with-headers [request]
  {:headers            {"X-Test-Header" "Hello!"}
   :undertow/websocket {}})

Middleware

Undertow adapter provides session middleware using Undertow session. By default, sessions will timeout after 30 minutes of inactivity.

Supported options:

(require '[ring.adapter.undertow.middleware.session :refer [wrap-session]])

(wrap-session handler {:http-only true})

License

Distributed under MIT License.