Convert HTTPoison Request into curl command
Today I learned how to convert a HTTPoison Request into a curl command, useful for logs. This might be useful to someone else, so I am sharing:
defmodule MyHTTP do
def curl(%HTTPoison.Request{} = req) do
headers = req.headers |> Enum.map(fn {k, v} -> "-H \"#{k}: #{v}\"" end) |> Enum.join(" ")
body = req.body && req.body != "" && "-d '#{req.body}'" || nil
params = URI.encode_query(req.params || [])
url = [req.url, params] |> Enum.filter(& &1 != "") |> Enum.join("?")
[
"curl -v -X",
to_string(req.method),
headers,
body,
url,
";"
]
|> Enum.filter(& &1)
|> Enum.map(&String.trim/1)
|> Enum.filter(& &1 != "")
|> Enum.join(" ")
end
end
And here's an example of usage:
MyHTTP.curl(%HTTPoison.Request{
url: "https://til.hashrocket.com",
params: [q: "elixir"]
})
"curl -v -X get https://til.hashrocket.com?q=elixir ;"
Tweet