项目需求并不需要太复杂的http运行,只需要达到需求即可,所以并不打算深入研究cowboy,直接简单运用到项目中。
改自hello world
1..app
{application,qimiao,
[{description,"Socket acceptor pool for TCP protocols."},
{vsn,"1.2.1"},
{id, "1.2.1-dirty"},
{modules, ['qimiao_app','main_handler','qimiao_sup']},
{registered,[qimiao_sup]},
{applications,[kernel,stdlib]},
{mod,{qimiao_app,[]}},
{env,[]}]}.
2.qimiao_app.erl
%% @private
-module(qimiao_app).
-behaviour(application).
%% API.
-export([start/2]).
-export([stop/1]).
%% API.
start(_Type, _Args) ->
%需要先启动的库
ok = application:start(crypto),
ok = application:start(ranch),
ok = application:start(cowlib),
ok = application:start(cowboy),
reloader:start(), %热更
Dispatch = cowboy_router:compile([
{'_', [
{"/1000/", main_handler, [1000]}, %协议分发
{"/1001/", main_handler, [1001]}
]}
]),
{ok, _} = cowboy:start_clear(http, 100, [{port, 8080}], #{
env => #{dispatch => Dispatch}
}),
qimiao_sup:start_link().
stop(_State) ->
ok.
3.协议处理
%% @doc Hello world handler.
-module(main_handler).
-export([init/2]).
init(Req, Opts) ->
cowboy_req:reply(200, #{
<<"content-type">> => <<"text/plain">>
}, router(Opts), Req),
{ok, Req, Opts}.
% 请求转发处理协议
router([1000])->
"1000";
router([1001])->
"1001";
router(_)->
"-1".