Skip to content

Instantly share code, notes, and snippets.

@dry
Created December 2, 2012 14:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save dry/4188894 to your computer and use it in GitHub Desktop.
Save dry/4188894 to your computer and use it in GitHub Desktop.
Simple URL dispatcher for Mochiweb
-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)).
-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}
].
%% 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