Created
December 23, 2013 18:49
-
-
Save mokevnin/8102469 to your computer and use it in GitHub Desktop.
naming routes for cowboy
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
-module(routes). | |
-export([compile/0, generate_path/2, generate_url/3]). | |
compile() -> | |
List = [root, games, game, start_game], | |
cowboy_router:compile([ | |
%% {URIHost, list({URIPath, Handler, Opts})} | |
{'_', [route(Name) || Name <- List]} | |
]). | |
route(root) -> | |
{"/", welcome_handler, []}; | |
route(games) -> | |
{"/games", bullet_handler, [{handler, games_handler}]}; | |
route(game) -> | |
{"/games/:id", bullet_handler, [{handler, game_handler}]}; | |
route(start_game) -> | |
{"/games/:id/start", start_game_handler, []}. | |
generate_path(RouteName, Bindings) -> | |
Path = element(1, route(RouteName)), | |
GeneratedPath = lists:foldl(fun({Key, Value}, Acc) -> | |
re:replace(Acc, [":" | atom_to_list(Key)], to_string(Value), [global, {return, list}]) end, Path, Bindings), | |
list_to_binary(GeneratedPath). | |
generate_url(RouteName, Bindings, Host) -> | |
Path = generate_path(RouteName, Bindings), | |
<<"http://", Host/binary, Path/binary>>. | |
to_string(Value) when is_atom(Value) -> | |
atom_to_list(Value); | |
to_string(Value) when is_integer(Value) -> | |
integer_to_list(Value); | |
to_string(Value) when is_binary(Value) -> | |
binary_to_list(Value). |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment