I'm trying to set up a very simple, basic HTTP API in Elixir. I thought using Phoenix for such a thing is totally overkill, so wanted to do it simply by using Plug. And I can do it by setting up a basic Router like this:
defmodule Example.Router do
use Plug.Router
plug Plug.Logger
plug :match
plug :dispatch
get "/" do
data = do_something_with_conn(conn)
send_resp(conn, 200, Poison.encode!(data))
end
match _, do: send_resp(conn, 404, "Not Found")
end
However, I can't figure out how to connect this router to another Plug function. Say, somewhere I have this plug-compliant function:
defmodule RandomPlug do
import Plug.Conn
def random_plug(conn, opts) do
whatever(conn)
end
end
How do I connect it to the Router? I've tried using this syntax from the docs:
forward "/", to: RandomPlug.random_plug
And other variations, but I can't get it to compile and/or work. For example the version above complains about there being no random_plug/0 function.
Yes, I can get it to work with a whole Plug module (with init
and call
), but I want to figure out how to get it working with a function. Perhaps it will give me a better understanding of some Elixir specifics, and it should be possible according to the docs.