简体   繁体   中英

How to connect Plug.Router with Plug function

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM