Why does it not matter whether you use @behaviour or not?

If you follow the tutorial here:
https://hexdocs.pm/plug/readme.html#hello-world-websockets

You can create a Bandit http server that is upgraded upon request for /websocket to a websocket. This is done by passing into the WebSockAdapter the following command:

upgrade(conn, websock, state, opts)

Upgrades the provided Plug.Conn connection request to a WebSock connection using the provided WebSock compliant module as a handler.

But what is strange to me is the “WebSock” compliant module is this:

defmodule EchoServer do
  def init(options) do
    {:ok, options}
  end

  def handle_in({"ping", [opcode: :text]}, state) do
    {:reply, :ok, {:text, "pong"}, state}
  end

  def terminate(:timeout, state) do
    {:ok, state}
  end
end

It works whether or not you have an @behaviour WebSock in it. So what makes it “compliant”? How does it work as a “WebSock behavior” when it doesn’t even need to be specified as one?

Otherwise the elixir compiler will not know you are implementing a behaviour. With the @behaviour specified the compiler will warn you if you don’t implement the correct callbacks

The callbacks are dynamic so it works even if you don’t specify it but you will not get any help from the compiler without it

4 Likes