以下代码主要基于此处的示例:
唯一真正的区别是增加了主管:
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提示IO.puts'日志响应'每个http请求两次......
是什么原因造成的?
答案 0 :(得分:5)
在本地测试后,我认为第一个请求是针对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
请注意,[]
代表/
路径。