5

以下代码主要基于此处找到的示例:

http://hexdocs.pm/plug/

唯一真正的区别是增加了一个主管:

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 ,对于每个 http 请求,iex 会提示 IO.puts ' Log Response ' 两次...

是什么原因造成的?

4

1 回答 1

6

在本地测试后,我认为第一个请求是针对网站图标的。您可以看到,如果您添加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

请注意,[]代表/路径。

于 2015-04-13T21:45:20.427 回答