【问题标题】:Elixir - Simple Plug example hits the call method twice on each requestElixir - 简单插件示例在每个请求上两次调用调用方法
【发布时间】:2015-06-19 05:18:15
【问题描述】:

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

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 em>' 每个 http 请求两次...

是什么原因造成的?

【问题讨论】:

    标签: web-services http elixir erlang-otp phoenix-framework


    【解决方案1】:

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

    注意[] 代表/ 路径。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-28
      • 1970-01-01
      • 2012-10-06
      • 2012-02-23
      • 2013-12-10
      • 1970-01-01
      • 1970-01-01
      • 2010-11-12
      相关资源
      最近更新 更多