cowboy页面重定向的例子

创建工程

rebar-creator create-app testCowboy

 

testCowboy_app.erl

-module(testCowboy_app).

-behaviour(application).

-export([start/2, stop/1]).

-define(C_ACCEPTORS,  100).

start(_StartType, _StartArgs) ->
    application:start(crypto),
    application:start(cowlib),
    application:start(ranch),
    application:start(cowboy),

    Routes    = route_helper:get_routes(),
    Dispatch  = cowboy_router:compile(Routes),
    Port      = 8080,
    TransOpts = [{port, Port}],
    ProtoOpts = [
        {env, [
            {dispatch, Dispatch}]}
    ],
    cowboy:start_http(http, ?C_ACCEPTORS, TransOpts, ProtoOpts).

stop(_State) ->
    ok.

 

route_helper.erl

-module(route_helper).

-export([get_routes/0]).

get_routes() ->
    [
        {'_', [
        {"/redirect", redirect_handler, []}
        ]}
    ].

 

redirect_handler.erl

-module(redirect_handler).

-export([init/3]).
-export([handle/2]).
-export([terminate/3]).

init(_Transport, Req, []) ->
    {ok, Req, undefined}.

handle(Req, State) ->
    {ok, Reply} = cowboy_req:reply(
        302,
        [{<<"Location">>, <<"http://www.baidu.com">>}],
        <<"Redirecting with Header!">>,
        Req
    ),
    {ok, Reply, State}.

terminate(_Reason, _Req, _State) ->
    ok.

 

posted @ 2015-02-07 08:53  自由出土文物  阅读(368)  评论(0编辑  收藏  举报