码迷,mamicode.com
首页 > 其他好文 > 详细

cowboy的路由方式

时间:2015-02-13 18:02:41      阅读:244      评论:0      收藏:0      [点我收藏+]

标签:

直接贴代码

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,可以写,可以不写

cowboy的路由方式

标签:

原文地址:http://www.cnblogs.com/ziyouchutuwenwu/p/4290503.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!