Kob

Another way to compose “Plug”s.

Rational

An experiment to seek another way (no macro?) for composing “Plug”s. The idea is based on my experience from koajs.

Note

This package requires OTP 21.2, which was released on Dec 12, 2018.

Installation

def deps do
  [
    {:kob, "~> 0.1.1"},
  ]
end

Docs can be found at https://hexdocs.pm/kob.

Example

defmodule Kob.Example.Demo do
  def run() do
    Kob.new()
    |> Kob.use(fn next ->
      fn conn ->
        IO.puts("start middleware 1")
        conn = next.(conn)
        IO.puts("finish middleware 1")
        conn
      end
    end)
    |> Kob.use(fn next ->
      fn conn ->
        IO.puts("start middleware 2")
        conn = next.(conn)
        IO.puts("finish middleware 2")
        conn
      end
    end)
    |> Kob.use(Kob.plug(Plug.Logger, log: :debug))
    |> Kob.use(fn _ ->
      fn conn ->
        conn
        |> Plug.Conn.put_resp_content_type("text/plain")
        |> Plug.Conn.send_resp(200, "Hello world")
      end
    end)
    |> Kob.register_plug(MyKobPlug)

    {:ok, _} = Plug.Cowboy.http(MyKobPlug, [])
  end
end

Compare Kob and Plug

It’s encouraged to take a look with Kob’s source code to have better understanding of it. The core part is Kob.compose function, which is only a few lines of code.

The key design of Kob is two types:

This design has a few benefits:

Kob and Plug are interchangeable

License

MIT