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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With