Add Clacks.HTTP.head helper

This commit is contained in:
Shadowfacts 2020-05-20 17:42:10 -04:00
parent 0afe2d3b30
commit 411dcaa32e
Signed by: shadowfacts
GPG Key ID: 94A5AB95422746E5
2 changed files with 19 additions and 6 deletions

View File

@ -38,9 +38,8 @@ defmodule Clacks.ActivityPub.Fetcher do
Logger.debug("Attempting to fetch AP object at #{uri}") Logger.debug("Attempting to fetch AP object at #{uri}")
headers = [Accept: "application/activity+json, application/ld+json"] headers = [Accept: "application/activity+json, application/ld+json"]
opts = [hackney: Application.get_env(:clacks, :hackney_opts, [])]
with {:ok, %HTTPoison.Response{body: body}} <- Clacks.HTTP.get(uri, headers, opts), with {:ok, %HTTPoison.Response{body: body}} <- Clacks.HTTP.get(uri, headers),
{:ok, data} <- Jason.decode(body) do {:ok, data} <- Jason.decode(body) do
data data
else else

View File

@ -1,8 +1,22 @@
defmodule Clacks.HTTP do defmodule Clacks.HTTP do
require Logger require Logger
def get(url, headers \\ [], options \\ []) do @spec get(url :: String.t(), headers :: [{String.t(), String.t()}]) ::
case HTTPoison.get(url, headers, options) do {:ok, HTTPoison.Response.t()} | {:error, String.t()}
def get(url, headers \\ []) do
fetch(:get, url, headers)
end
@spec head(url :: String.t(), headers :: [{String.t(), String.t()}]) ::
{:ok, HTTPoison.Response.t()} | {:error, String.t()}
def head(url, headers \\ []) do
fetch(:head, url, headers)
end
defp fetch(method, url, headers) do
opts = [hackney: Application.get_env(:clacks, :hackney_opts, [])]
case HTTPoison.request(method, url, "", headers, opts) do
{:ok, %HTTPoison.Response{status_code: status_code} = response} {:ok, %HTTPoison.Response{status_code: status_code} = response}
when status_code in 200..299 -> when status_code in 200..299 ->
{:ok, response} {:ok, response}
@ -24,7 +38,7 @@ defmodule Clacks.HTTP do
end end
Logger.debug("Got 301 redirect from #{url} to #{new_url}") Logger.debug("Got 301 redirect from #{url} to #{new_url}")
get(new_url, headers, options) fetch(method, new_url, headers)
_ -> _ ->
{:error, "Missing Location header for redirect"} {:error, "Missing Location header for redirect"}
@ -40,7 +54,7 @@ defmodule Clacks.HTTP do
{:error, "HTTP #{status_code}"} {:error, "HTTP #{status_code}"}
{:error, %HTTPoison.Error{reason: reason}} -> {:error, %HTTPoison.Error{reason: reason}} ->
{:error, reason} {:error, inspect(reason)}
end end
end end
end end