Reputation: 2574
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.
Upvotes: 1
Views: 546
Reputation: 222388
I just read the source of Plug.Builder
and did not find a way to specify a module and function name combination in plug
. It seems to be limited to either a function name or a module name (in which case it'll call module.init/2
). But, you can import
the functions from the module and then treat the imported functions as local functions:
defmodule Example.Router do
use Plug.Router
...
import RandomPlug
plug :random_plug
end
Upvotes: 1