cowboy的路由方式
直接贴代码
route_helper.erl
-module(route_helper). -export([get_routes/0]). get_routes() -> [ {'_', [ %% 路由的一些情况 { "/catch_all_handler/[...]", catch_all_handler, [] }, { "/:aa/:bb/[:c]", test_handler, [aaa] } ]} ].
catch_all_handler里面处理以catch_all_handler开始的所有url请求
catch_all_handler.erl
-module(catch_all_handler). -export([init/3]). -export([handle/2]). -export([terminate/3]). init(_Transport, Req, []) -> {ok, Req, undefined}. handle(Req, State) -> {Path,_} = cowboy_req:path(Req), {PathList, _} = cowboy_req:path_info(Req), lists:foreach( fun(PathArg)-> io:format("catch_all_handler path is ~p, args ~p~n",[Path,PathArg]) end, PathList ), {ok, Req, State}. terminate(_Reason, _Req, _State) -> ok.
test_handler.erl
-module(test_handler). -export([init/3]). -export([handle/2]). -export([terminate/3]). init(_Transport, Req, [Options]) -> io:format("options ~p~n",[Options]), {ok, Req, undefined}. handle(Req, State) -> {PathInfo,_} = cowboy_req:path(Req), {Arg1,_} = cowboy_req:binding(aa,Req), {Arg2,_} = cowboy_req:binding(bb,Req), io:format("test_handler path is ~p, arg1 ~p,arg2 ~p~n",[PathInfo,Arg1,Arg2]), {ok, Req, State}. terminate(_Reason, _Req, _State) -> ok.
init里面的Option就是aaa,cowboy_req:bing()来获取后面的url,[:c]为可选url,可以写,可以不写