Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elixir - Simple Plug example hits the call method twice on each request

The following code is largely based on the example found here:

http://hexdocs.pm/plug/

The only real difference is the addition of a supervisor:

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

Here's the plug itself:

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

When I run the application with iex -S mix, open a browser, then hit localhost, the iex prompt IO.puts 'Log Response' twice for each http request...

What's causes that?

like image 325
Charlie Avatar asked Apr 13 '15 19:04

Charlie


1 Answers

After testing locally I think the first request is for a favicon. You can see that if you add IO.inspect(conn.path_info) - it will output ["favicon.ico"].

You can easily add matching on the path like so:

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

Note that the [] represents the / path.

like image 115
Paweł Obrok Avatar answered Nov 04 '22 16:11

Paweł Obrok