PlugSocket - easily add Cowboy websockets to your Plug.Router

Hey all,

I created a library that allows you to easily add Cowboy websockets to your Plug.Router.

Check out the docs!

Check out the code!

Example

Add the PlugSocket to your router. Then use the socket/2 macro as necessary. E.g.,

defmodule MyApp.Router do
  use Plug.Router
  use PlugSocket

  socket "/my-socket", MyApp.MySocket

  plug :match
  plug :dispatch

  get "/" do
    send_resp(conn, 200, "hello world")
  end
end

Each module you pass to socket/3 must implement the :cowboy_websocket_handler
behavior. Note that because socket/3 is not a Plug, it is not part of any
plug pipeline you create in your router. It is a “DSL” onto itself.

Next, you need to ensure our websockets are added to the Cowboy dispatch:

def start(_type, _args) do
  children = [
    {Plug.Cowboy, scheme: :http, plug: MyApp.Router, options: [
      dispatch: PlugSocket.plug_cowboy_dispatch(MyApp.Router)
    ]}
  ]

  opts = [strategy: :one_for_one, name: MyApp.Supervisor]
  Supervisor.start_link(children, opts)
end

This registers your sockets with the Cowboy dispatcher. You can now
start the application and navigate to your socket path in your client
and see that it is now routing!


That’s all - the library is actually REALLY simple, I think no more than 20 lines of code. But the problem has come up time and again so I figured might as well make it a package.

Technically this library does not use or leverage Plug at all per se. But I couldn’t think of a better name, since most of the time people are looking for “how to use sockets with plug” I figure I may as well call it PlugSocket.

Cheers,
Kevin

8 Likes

oh this is great
thank you for your effort :relaxed: