$ cd ..
Initialize a new git repository and use rebar to create the skeleton for a new Erlang app. I decided to call my application erlblog. Call your application differently, replacing every occurrence of erlblog with your favourite application name in the instructions below. Please note that this is not optional, since two applications cannot have the same name on Heroku and you don’t dare to clash with my own application.
]}.
Add cowboy to the list of applications in your .app.src file. Also, set the http_port environment variable to 8080 (see next paragraphs).
]}.
修改erlblog_app.erl文件的start/2函数,当erlblog应用程序启动时Cowboy才能启动一个进程池,接收用户连接
配置Cowboy路由分派器为一个单一的路径,所有的请求都路由到根路径"/",并使用erlblog_handler处理用户请求
修改模块内容:
$ cat src/erlblog_app.erl
-module(erlblog_app).
-behaviour(application).
%% Application callbacks
-export([start/2, stop/1]).
-define(C_ACCEPTORS, 100).
%% ===================================================================
%% Application callbacks
%% ===================================================================
start(_StartType, _StartArgs) ->
Routes = routes(),
Dispatch = cowboy_router:compile(Routes),
Port = port(),
TransOpts = [{port, Port}],
ProtoOpts = [{env, [{dispatch, Dispatch}]}],
{ok, _} = cowboy:start_http(http, ?C_ACCEPTORS, TransOpts, ProtoOpts),
erlblog_sup:start_link().
stop(_State) ->
ok.
%% ===================================================================
%% Internal functions
%% ===================================================================
routes() ->
[
{‘_‘, [
{"/", erlblog_handler, []}
]}
].
port() ->
case os:getenv("PORT") of
false ->
{ok, Port} = application:get_env(http_port),
Port;
Other ->
list_to_integer(Other)
end.
添加请求处理模块
$ cat src/erlblog_handler.erl
-module(erlblog_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.
Finally, let’s create an interface module which will be responsible for starting your erlblog application together with all its dependencies.
erlblog模块内容:
$ cat src/erlblog.erl
-module(erlblog).
-export([start/0]).
start() ->
ok = application:start(crypto),
ok = application:start(ranch),
ok = application:start(cowboy),
ok = application:start(erlblog).
使用rebar 获得Cowboy程序以及依赖程序并编译
$ ./rebar get-deps compile
启动程序
$ erl -pa ebin deps/*/ebin -s erlblog
1> application:which_applications().
最后使用浏览器访问测试