zoukankan      html  css  js  c++  java
  • 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.
    复制代码
  • 相关阅读:
    hibernate 笔记二
    log4j详解及简易搭建
    hibernate 笔记一
    【工作心得】timesten应用(安装配置篇)
    【转】boost 内存池
    【转】基于Socket的UDP和TCP编程介绍
    【工作心得】timesten应用(开发篇)
    【读书笔记】UNIX进程间通信
    【读书笔记】硬链接与软链接
    【转】Linux Socket编程
  • 原文地址:https://www.cnblogs.com/ziyouchutuwenwu/p/4278069.html
Copyright © 2011-2022 走看看