@@ -1,7 +1,7 @@
11{-# LANGUAGE OverloadedStrings #-}
22module Network.Wai.Handler.WebSockets
3− ( websocketsApp
4− , websocketsOr
3+ ( websocketsOr
4+ , websocketsApp
55 , isWebSocketsReq
66 , getRequestHead
77 , runWebSockets
@@ -18,11 +18,38 @@ import qualified Network.WebSockets.Connection as WS
1818import qualified Network.WebSockets.Stream as WS
1919
2020--------------------------------------------------------------------------------
21+-- | Returns whether or not the given 'Wai.Request' is a WebSocket request.
2122isWebSocketsReq :: Wai.Request -> Bool
2223isWebSocketsReq req =
2324 fmap CI.mk (lookup "upgrade" $ Wai.requestHeaders req) == Just "websocket"
2425
2526--------------------------------------------------------------------------------
27+-- | Upgrade a @websockets@ 'WS.ServerApp' to a @wai@ 'Wai.Application'. Uses
28+-- the given backup 'Wai.Application' to handle 'Wai.Request's that are not
29+-- WebSocket requests.
30+--
31+-- @
32+-- websocketsOr opts ws_app backup_app = \\req send_response ->
33+-- __case__ 'websocketsApp' opts ws_app req __of__
34+-- 'Nothing' -> backup_app req send_response
35+-- 'Just' res -> send_response res
36+-- @
37+--
38+-- For example, below is an 'Wai.Application' that sends @"Hello, client!"@ to
39+-- each connected client.
40+--
41+-- @
42+-- app :: 'Wai.Application'
43+-- app = 'websocketsOr' 'WS.defaultConnectionOptions' wsApp backupApp
44+-- __where__
45+-- wsApp :: 'WS.ServerApp'
46+-- wsApp pending_conn = do
47+-- conn <- 'WS.acceptRequest' pending_conn
48+-- 'WS.sendTextData' conn ("Hello, client!" :: 'Data.Text.Text')
49+--
50+-- backupApp :: 'Wai.Application'
51+-- backupApp = 'Wai.respondLBS' 'Network.HTTP.Types.status400' [] "Not a WebSocket request"
52+-- @
2653websocketsOr :: WS.ConnectionOptions
2754 -> WS.ServerApp
2855 -> Wai.Application
@@ -33,6 +60,11 @@ websocketsOr opts app backup req sendResponse =
3360 Just res -> sendResponse res
3461
3562--------------------------------------------------------------------------------
63+-- | Handle a single @wai@ 'Wai.Request' with the given @websockets@
64+-- 'WS.ServerApp'. Returns 'Nothing' if the 'Wai.Request' is not a WebSocket
65+-- request, 'Just' otherwise.
66+--
67+-- Usually, 'websocketsOr' is more convenient.
3668websocketsApp :: WS.ConnectionOptions
3769 -> WS.ServerApp
3870 -> Wai.Request
@@ -55,7 +87,7 @@ getRequestHead req = WS.RequestHead
5587 (Wai.isSecure req)
5688
5789--------------------------------------------------------------------------------
58−---- | Internal function to run the WebSocket io-streams using the conduit library
90+-- | Internal function to run the WebSocket io-streams using the conduit library.
5991runWebSockets :: WS.ConnectionOptions
6092 -> WS.RequestHead
6193 -> (WS.PendingConnection -> IO a)