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.
复制代码
原文地址:https://www.cnblogs.com/ziyouchutuwenwu/p/4278069.html