This repository has been archived by the owner on Dec 26, 2020. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 48
/
http_util.erl
83 lines (72 loc) · 2 KB
/
http_util.erl
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
-module(http_util).
-export([
decode_body/3,
add_cors_headers/1,
log_request/1,
log_response/4
]).
-define(INVALID_JSON, <<"Invalid json">>).
log_request(Req) ->
{Headers, _} = cowboy_req:headers(Req),
{Method, _} = cowboy_req:method(Req),
{Path, _} = cowboy_req:path(Req),
{{Ip, Port}, _} = cowboy_req:peer(Req),
log:http(#{
peer => #{
ip => list_to_binary(inet:ntoa(Ip)),
port => Port
},
headers => Headers,
method => Method,
path => Path,
type => request
}),
Req.
log_request_body(Body) ->
log_body(Body, request_body).
log_response_body(Body) ->
log_body(Body, response_body).
log_body(<<>>, _) ->
ok;
log_body(Body, Type) ->
log:http(#{
body => Body,
type => Type
}).
log_response(Status, Headers, Body, Req) ->
log:http(#{
status => Status,
headers => format_headers(Headers),
type => response
}),
log_response_body(Body),
Req.
format_headers([]) ->
[];
format_headers([{K, V}|Rest]) when is_list(V) ->
[{K, list_to_binary(V)}|format_headers(Rest)];
format_headers([{K, V}|Rest]) ->
[{K, V}|format_headers(Rest)].
decode_body(F, Req, State) ->
{ok, Body, Req2} = cowboy_req:body(Req),
log_request_body(Body),
case jsx:is_json(Body) of
true ->
Data = jsx:decode(Body),
F(Data, Req2, State);
false ->
Payload = jsx:encode([{message, ?INVALID_JSON}]),
{ok, Req3} = cowboy_req:reply(400, [], Payload, Req2),
{halt, Req3, State}
end.
add_cors_headers(Req) ->
Headers = [
{<<"access-control-allow-methods">>, <<"POST, OPTIONS">>},
{<<"access-control-allow-origin">>, <<"*">>},
{<<"access-control-allow-headers">>, <<"Content-Type">>}
],
set_headers(Headers, Req).
set_headers(Headers, Req) ->
lists:foldl(fun({Name, Value}, R) ->
cowboy_req:set_resp_header(Name, Value, R)
end, Req, Headers).