Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Post processing the controller response with a plug in phoenix

How can I create a plug that e.g. turns the body of the response to upper case if the content-type is text/plain? In other middlewares you'd call resp = next(conn, params) and then modify resp but I haven't seen this in plug.

like image 857
Cristian Garcia Avatar asked Sep 21 '15 20:09

Cristian Garcia


1 Answers

You can define a plug that uses register_before_send/2 and check the content-type header of the response (please note that Plug expects headers to be lowercase). A naive implementation (no error checking) would be:

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

resp/3 is used as send_resp/3 will cause an infinite loop and you will have to restart your server.

like image 187
Gazler Avatar answered Oct 13 '22 17:10

Gazler