summaryrefslogtreecommitdiff
path: root/src/r3_hex_http_httpc.erl
blob: 0be9d16c18252c469fc349a9b4bc76ff55c5ef1c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
%% Vendored from hex_core v0.5.0, do not edit manually

%% @hidden

-module(r3_hex_http_httpc).
-behaviour(r3_hex_http).
-export([request/5]).

%%====================================================================
%% API functions
%%====================================================================

request(Method, URI, ReqHeaders, Body, AdapterConfig) ->
    Profile = maps:get(profile, AdapterConfig, default),
    Request = build_request(URI, ReqHeaders, Body),
    {ok, {{_, StatusCode, _}, RespHeaders, RespBody}} =
        httpc:request(Method, Request, [], [{body_format, binary}], Profile),
    RespHeaders2 = load_headers(RespHeaders),
    {ok, {StatusCode, RespHeaders2, RespBody}}.

%%====================================================================
%% Internal functions
%%====================================================================

build_request(URI, ReqHeaders, Body) ->
    build_request2(binary_to_list(URI), dump_headers(ReqHeaders), Body).

build_request2(URI, ReqHeaders, undefined) ->
    {URI, ReqHeaders};
build_request2(URI, ReqHeaders, {ContentType, Body}) ->
    {URI, ReqHeaders, ContentType, Body}.

dump_headers(Map) ->
    maps:fold(fun(K, V, Acc) ->
        [{binary_to_list(K), binary_to_list(V)} | Acc] end, [], Map).

load_headers(List) ->
    lists:foldl(fun({K, V}, Acc) ->
        maps:put(list_to_binary(K), list_to_binary(V), Acc) end, #{}, List).