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を押すと、iex プロンプト IO.puts ' Log Response ' が http 要求ごとに 2 回表示されます...

それは何が原因ですか?

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 に答える