使用插入凤凰后处理控制器响应

Cri*_*cia 8 elixir phoenix-framework

我怎样才能创建一个插件是如转动body的响应为大写,如果content-typetext/plain?在其他中间件中,您调用resp = next(conn, params)然后修改resp但我没有在插件中看到它.

Gaz*_*ler 13

您可以定义使用register_before_send/2的插件并检查content-type响应的标头(请注意Plug期望标头为小写).一个天真的实现(没有错误检查)将是:

defmodule Plug.UpperCaser do
  @behaviour Plug

  import Plug.Conn

  def init(opts), do: opts

  def call(conn, _opts) do
    register_before_send(conn, fn(conn) ->
      [content_type | _tail] = get_resp_header(conn, "content-type")
      if String.contains?(content_type, "text/plain") do
        resp(conn, conn.status, conn.resp_body |> to_string |> String.upcase)
      else
        conn
      end
    end)
  end
end
Run Code Online (Sandbox Code Playgroud)

resp/3用作send_resp/3将导致无限循环,您将不得不重新启动服务器.