cowboy的中间件

想不到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}]},
        {middlewares, [cowboy_router, test_middleware, cowboy_handler]}
    ],
    cowboy:start_http(http, ?C_ACCEPTORS, TransOpts, ProtoOpts).

stop(_State) ->
    ok.

 

route_helper.erl

复制代码
-module(route_helper).

-export([get_routes/0]).

get_routes() ->
    [
        {'_', [
            {"/", test_handler, []}
        ]}
    ].
复制代码

 

test_middleware.erl

-module(test_middleware).
-behaviour(cowboy_middleware).

-export([execute/2]).

%% 这个是回调函数
execute(Req, Env) ->
    {PathInfo,_} = cowboy_req:path(Req),
    Path = binary_to_list(PathInfo),
    io:format("Path is ~p~n",[Path]),
    {ok, Req, Env}.

 

test_handler.erl

复制代码
-module(test_handler).

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

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

handle(Req, State) ->
    {ok, Req2} = cowboy_req:reply(200, [], <<"Hello world!">>, Req),
    {ok, Req2, State}.

terminate(_Reason, _Req, _State) ->
    ok.
复制代码

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值