Created
December 28, 2013 18:05
-
-
Save Zert/8162261 to your computer and use it in GitHub Desktop.
This file contains 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
-module (cowbug_handler). | |
-export([start/0]). | |
-export([init/3, handle/2, terminate/3]). | |
start() -> | |
[application:start(A) || | |
A <- | |
[ | |
crypto, | |
asn1, | |
public_key, | |
ssl, | |
lhttpc, | |
ranch, | |
cowlib, | |
cowboy | |
]], | |
Dispatch = | |
cowboy_router:compile( | |
[ | |
{'_', [ | |
% Handlers are here... | |
{<<"/api/one">>, ?MODULE, {one}}, | |
{<<"/api/two">>, ?MODULE, {two}}, | |
{'_', ?MODULE, not_implemented} | |
]} | |
]), | |
cowboy:start_http(crm_api_http_listener, 10, | |
[{port, 8800}], | |
[{env, [{dispatch, Dispatch}]}] | |
), | |
timer:sleep(1000), | |
lhttpc:request("http://localhost:8800/api/one?a=1", get, [], "a=1", 5000), % good reply, which is cause of error in the next reqest | |
lhttpc:request("http://localhost:8800/api/two", post, [], "a=1", 5000), % bad reply | |
lhttpc:request("http://localhost:8800/api/two", post, [], "a=1", 5000), % good reply again | |
ok. | |
init({tcp, http}, Request, Opts) -> | |
{ok, Request, Opts}. | |
handle(Request, {one} = State) -> | |
{Method, Request2} = cowboy_req:method(Request), | |
Body = | |
case Method of | |
<<"GET">> -> | |
<<"OK">>; | |
_Other -> | |
io:format("Bad request method: ~p~n", [Method]), | |
<<"ERROR">> | |
end, | |
{ok, Response} = cowboy_req:reply(200, [], Body, Request2), | |
{ok, Response, State}; | |
handle(Request, {two} = State) -> | |
{Method, Request2} = cowboy_req:method(Request), | |
Body = | |
case Method of | |
<<"POST">> -> | |
<<"OK">>; | |
_Other -> | |
io:format("Bad request method: ~p~n", [Method]), | |
<<"ERROR">> | |
end, | |
{ok, Response} = cowboy_req:reply(200, [], Body, Request2), | |
{ok, Response, State}; | |
handle(Request, State) -> | |
{ok, Response} = cowboy_req:reply(501, [], list_to_binary("This call is not supported!\nNode: " ++ atom_to_list(node())), Request), | |
{ok, Response, State}. | |
terminate(_Reason, _Request, _State) -> | |
ok. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment