Skip to content

Instantly share code, notes, and snippets.

@hosh
Created October 13, 2018 00:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hosh/93d2d88ab31eeb3520737d6fc54ac484 to your computer and use it in GitHub Desktop.
Save hosh/93d2d88ab31eeb3520737d6fc54ac484 to your computer and use it in GitHub Desktop.
Kludge to add additional body_params parsing for HTTP verbs such as REPORT
defmodule Legalio.Plug.ConvertToPost do
@moduledoc """
A Plug to convert a list of methods to POST so
that body_params can be populated
"""
@behaviour Elixir.Plug
alias Elixir.Plug.Conn
def init(opts) do
{methods, _opts} = Keyword.pop(opts, :methods)
unless methods do
raise ArgumentError, "Legalio.Plug.ConvertToPost requires a list of methods given in :methods"
end
{methods}
end
def call(%Conn{method: method, private: private} = conn, {convert_methods}) do
{method, convert_methods} |> IO.inspect
if method in convert_methods do
%{conn | method: "POST", private: Map.put(private, :real_method, method)} |> IO.inspect
else
conn
end
end
def call(conn, _), do: conn
end
defmodule Legalio.Plug.RestoreFromPost do
@moduledoc """
A Plug that reads the real_method value stored in the private databag in
conn and restores the request method. To be used in conjunction with
ConvertToPost.
In the long-run, Plug.Parsers itself should be modified to accept additional
HTTP methods.
"""
@behaviour Elixir.Plug
alias Elixir.Plug.Conn
def init(_) do
{}
end
def call(%Conn{method: "POST", private: %{real_method: real_method}} = conn, _) do
%{conn | method: real_method }
end
def call(conn, _), do: conn
end
plug Legalio.Plug.ConvertToPost, methods: ["REPORT"]
plug Plug.Parsers,
parsers: [:urlencoded, :multipart, :json],
pass: ["*/*"],
json_decoder: Poison
plug Legalio.Plug.RestoreFromPost
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment