Created
December 2, 2012 14:11
-
-
Save dry/4188894 to your computer and use it in GitHub Desktop.
Simple URL dispatcher for Mochiweb
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(dispatcher). | |
-export([dispatch/2]). | |
dispatch(_, []) -> none; | |
dispatch(Req, [{Regexp, Handler}|T]) -> | |
"/" ++ Path = Req:get(path), | |
Method = Req:get(method), | |
Match = re:run(Path, Regexp, [global, {capture, all_but_first, list}]), | |
case Match of | |
{match, [MatchList]} -> | |
% We found a regexp that matches the current URL path | |
case length(MatchList) of | |
0 -> | |
% We didn't find any URL parameters | |
Action = convert_method_to_action(Method), | |
Handler:Action(Req); | |
Length when Length > 0 -> | |
% We pass URL parameters to the function | |
Args = lists:append([[Method, Req], MatchList]), | |
Action = convert_method_to_action(Method), | |
apply(Handler, Action, Args) | |
end; | |
_ -> | |
dispatch(Req, T) | |
end. | |
convert_method_to_action(Method) -> | |
List = atom_to_list(Method), | |
Action = string:sub_string(List, 1, length(List)), | |
list_to_atom(string:to_lower(Action)). |
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(router). | |
-export([urls/0]). | |
%% Handler modules have functions corresponding | |
%% to lowercased HTTP methods (get, post etc) | |
urls() -> [ | |
{"^1.0/update$", handler_update}, | |
{"^1.0/check$", handler_check} | |
]. |
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
%% Mochiweb loop | |
loop(Req, DocRoot) -> | |
"/" ++ Path = Req:get(path), | |
try | |
case dispatcher:dispatch(Req, router:urls()) of | |
none -> | |
% No request handler found | |
Req:not_found(); | |
Response -> | |
Response | |
end | |
catch | |
Type:What -> | |
%% Error handling | |
... | |
end. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment