$ 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().
最後使用瀏覽器訪問測試