• 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.
    复制代码
  • 相关阅读:
    bzoj4028 [HEOI2015]公约数数列
    bzoj4766 文艺计算姬
    bzoj4241 历史研究
    bzoj3744 Gty的妹子序列
    bzoj4540 [Hnoi2016]序列
    uoj#228 基础数据结构练习题
    bzoj2467 [中山市选2010]生成树
    bzoj2125 最短路
    bzoj4800 [Ceoi2015]Ice Hockey World Championship
    bzoj2463 [中山市选2009]谁能赢呢?
  • 原文地址:https://www.cnblogs.com/ziyouchutuwenwu/p/4278069.html
Copyright © 2020-2023  润新知