以下代码主要基于此处的示例:
唯一真正的区别是增加了一名主管:
defmodule MyApi.Supervisor do use Supervisor def start_link do Supervisor.start_link(__MODULE__,:ok) end def init(:ok) do children = [ Plug.Adapters.Cowboy.child_spec( :http,MyApi.BasicServer,[],[ port: 80 ] ) ] supervise(children,strategy: :one_for_one) end end
这是插件本身:
defmodule MyApi.BasicServer do import Plug.Conn import Process def init(options) do IO.puts("Log Init") options end def call(conn,_opts) do IO.puts("Log Response") conn |> put_resp_content_type("text/plain") |> send_resp(200,"Hello world") end end
当我使用iex -S mix运行应用程序时,打开浏览器,然后点击localhost,iex提示每次http请求的IO.puts’Log Response’两次…
是什么原因造成的?
解决方法
在本地测试后,我认为第一个请求是针对favicon.您可以看到,如果添加IO.inspect(conn.path_info) – 它将输出[“favicon.ico”].
您可以轻松地在路径上添加匹配,如下所示:
def call(conn = %{path_info: []},_opts) do conn |> put_resp_content_type("text/plain") |> send_resp(200,"Hello world") end def call(conn,_) do conn |> put_resp_content_type("text/plain") |> send_resp(404,"Not found") end
请注意,[]表示/ path.