Created
April 9, 2012 16:05
-
-
Save tsloughter/2344451 to your computer and use it in GitHub Desktop.
cowboy rest example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
%% @private | |
-spec init(list()) -> {ok, {SupFlags::any(), [ChildSpec::any()]}} | | |
ignore | {error, Reason::any()}. | |
init([]) -> | |
Dispatch = [ | |
%% {Host, list({Path, Handler, Opts})} | |
{'_', [{[<<"graphs">>, graph], kw_handler, []}]} | |
], | |
RestartStrategy = one_for_one, | |
MaxRestarts = 1000, | |
MaxSecondsBetweenRestarts = 3600, | |
SupFlags = {RestartStrategy, MaxRestarts, MaxSecondsBetweenRestarts}, | |
Restart = permanent, | |
Shutdown = 2000, | |
Type = worker, | |
AChild = {cowboy, {cowboy, start_listener, [http, 100, cowboy_tcp_transport | |
, [{port, 8080}], cowboy_http_protocol, [{dispatch, Dispatch}]]}, | |
Restart, Shutdown, Type, [cowboy]}, | |
{ok, {SupFlags, [AChild]}}. | |
-module(kw_handler). | |
-export([init/3, | |
allowed_methods/2, | |
content_types_accepted/2, | |
content_types_provided/2, | |
get_json/2, | |
put_json/2]). | |
init(_Transport, _Req, _Opts) -> | |
{upgrade, protocol, cowboy_http_rest}. | |
allowed_methods(Req, State) -> | |
{['HEAD', 'GET', 'POST', 'PUT'], Req, State}. | |
content_types_accepted(Req, State) -> | |
{[{{<<"application">>, <<"json">>, []}, put_json}], Req, State}. | |
content_types_provided(Req, State) -> | |
{[{{<<"application">>, <<"json">>, []}, get_json}], Req, State}. | |
put_json(Req, State) -> | |
{ok, Body, Req1} = cowboy_http_req:body(Req), | |
{Series, Req2} = cowboy_http_req:binding(graph, Req1), | |
kc_main:add(Series, jiffy:decode(Body)), | |
{true, Req2, State}. | |
get_json(Req, State) -> | |
{Series, Req1} = cowboy_http_req:binding(graph, Req), | |
{jiffy:encode(kc_main:get(Series)), Req1, State}. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
They now take binary not atoms
so
allowed_methods(Req, State) ->
{[<<"HEAD">>, <<"GET">>, <<"POST">>], Req, State}.