forked from cybergrind/rebar-templates
-
Notifications
You must be signed in to change notification settings - Fork 1
/
cowboy_rest.erl
73 lines (60 loc) · 2.19 KB
/
cowboy_rest.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
%%%-------------------------------------------------------------------
%%% @author {{author_name}} <{{{author_email}}>
%%% @copyright (C) {{copyright_year}}, {{copyright_owner}}
%%% @doc
%%%
%%% @end
%%% Created : {{now_ts}} by {{author_name}} <{{author_email}}>
%%%-------------------------------------------------------------------
-module('{{handlerid}}_rest').
%%%===================================================================
%% API
%%%===================================================================
-export([]).
%% Cowboy REST handler callbacks
-export([init/2,
allowed_methods/2,
content_types_provided/2,
content_types_accepted/2,
resource_exists/2]).
%%%===================================================================
%%% API
%%%===================================================================
%%%===================================================================
%%% Cowboy REST handler callbacks
%%%===================================================================
init(Req, Opts) ->
{cowboy_rest, Req, Opts}.
allowed_methods(Req, State) ->
{[<<"GET">>, <<"POST">>], Req, State}.
content_types_provided(Req, State) ->
{[
{<<"text/html">>, resource_to_html},
{<<"application/json">>, resource_to_json},
], Req, State}.
content_types_accepted(Req, State) ->
{[{{<<"application">>, <<"x-www-form-urlencoded">>, []}, create_resource}],
Req, State}.
resource_exists(Req, _State) ->
case cowboy_req:binding(id, Req) of
undefined ->
{true, Req, index};
Id ->
{true, Req, Id}
end.
%%%===================================================================
%%% Internal functions
%%%===================================================================
resource_to_html(Req, Paste) ->
{"<html>BODY</html>", Req, Paste}.
resource_to_json(Req, index) ->
{"{}", Req, index}.
create_resource(Req, State) ->
Id = random:uniform(1024),
{ok, [{<<"resource">>, Resource}], Req2} = cowboy_req:body_qs(Req),
case cowboy_req:method(Req2) of
<<"POST">> ->
{{true, <<$/, Id/binary>>}, Req2, State};
_ ->
{true, Req2, State}
end.