Browse Source

Add Clacks.HTTP.head helper

master
Shadowfacts 1 year ago
parent
commit
411dcaa32e
Signed by: shadowfacts GPG Key ID: 94A5AB95422746E5
2 changed files with 19 additions and 6 deletions
  1. +1
    -2
      lib/clacks/activitypub/fetcher.ex
  2. +18
    -4
      lib/clacks/http.ex

+ 1
- 2
lib/clacks/activitypub/fetcher.ex View File

@ -38,9 +38,8 @@ defmodule Clacks.ActivityPub.Fetcher do
Logger.debug("Attempting to fetch AP object at #{uri}")
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
data
else


+ 18
- 4
lib/clacks/http.ex View File

@ -1,8 +1,22 @@
defmodule Clacks.HTTP do
require Logger
def get(url, headers \\ [], options \\ []) do
case HTTPoison.get(url, headers, options) do
@spec get(url :: String.t(), headers :: [{String.t(), String.t()}]) ::
{: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}
when status_code in 200..299 ->
{:ok, response}
@ -24,7 +38,7 @@ defmodule Clacks.HTTP do
end
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"}
@ -40,7 +54,7 @@ defmodule Clacks.HTTP do
{:error, "HTTP #{status_code}"}
{:error, %HTTPoison.Error{reason: reason}} ->
{:error, reason}
{:error, inspect(reason)}
end
end
end

Loading…
Cancel
Save