1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.HTTP do
10 alias Pleroma.HTTP.Connection
11 alias Pleroma.HTTP.RequestBuilder, as: Builder
16 Builds and perform http request.
19 `method` - :get, :post, :put, :delete
22 `headers` - a keyworld list of headers, e.g. `[{"content-type", "text/plain"}]`
23 `options` - custom, per-request middleware or adapter options
26 `{:ok, %Tesla.Env{}}` or `{:error, error}`
29 def request(method, url, body \\ "", headers \\ [], options \\ []) do
31 process_request_options(options)
32 |> process_sni_options(url)
33 |> process_adapter_options()
35 params = Keyword.get(options, :params, [])
38 |> Builder.method(method)
39 |> Builder.headers(headers)
40 |> Builder.opts(options)
42 |> Builder.add_param(:body, :body, body)
43 |> Builder.add_param(:query, :query, params)
45 |> (&Tesla.request(Connection.new(), &1)).()
48 defp process_sni_options(options, nil), do: options
50 defp process_sni_options(options, url) do
52 host = uri.host |> to_charlist()
55 "https" -> options ++ [ssl: [server_name_indication: host]]
60 def process_adapter_options(options) do
61 adapter_options = Pleroma.Config.get([:http, :adapter], [])
63 options ++ [adapter: adapter_options]
66 def process_request_options(options) do
67 config = Application.get_env(:pleroma, :http, [])
68 proxy = Keyword.get(config, :proxy_url, nil)
72 _ -> options ++ [proxy: proxy]
79 See `Pleroma.HTTP.request/5`
81 def get(url, headers \\ [], options \\ []),
82 do: request(:get, url, "", headers, options)
85 Performs POST request.
87 See `Pleroma.HTTP.request/5`
89 def post(url, body, headers \\ [], options \\ []),
90 do: request(:post, url, body, headers, options)