ErlangとCowboyを使ってHelloWorld

実施環境:
OS: CentOS
Erlang: Eshell V6.4
Cowboy


erlang.mkのビルドシステムを使用するための準備

作業ディレクトリの作成
$ mkdir hello_erlang && cd hello_erlang


erlang.mkのダウンロード
$ wget https://raw.githubusercontent.com/ninenines/erlang.mk/master/erlang.mk


アプリケーション起動のためのブートストラップを作成
$ make -f erlang.mk bootstrap bootstrap-rel
$ make


作業ディレクトリにできたファイルの確認
$ tree --charset=o -L 2
.

-- Makefile
-- _rel
`-- hello_erlang_release
-- ebin
-- hello_erlang.app
-- hello_erlang_app.beam
`-- hello_erlang_sup.beam
-- erlang.mk
-- rel
-- sys.config
`-- vm.args
-- relx
-- relx.config

`-- src
|-- hello_erlang.app.src
|-- hello_erlang_app.erl
`-- hello_erlang_sup.erl


Cowboyのセットアップ

生成されたMakefileにCowboyを追加する
$ vim Makefile

PROJECT = hello_erlang
DEPS = cowboy
include erlang.mk


アプリケーションリソースファイルにcowboyの依存を追加する
$vim src/hello_erlang.app.src

{application, hello_erlang, [
{description, "Hello Erlang!"},
{vsn, "0.1.0"},
{modules, },
{registered,
},
{applications, [
kernel,
stdlib,
cowboy
]},
{mod, {hello_erlang_app, }},
{env,
}
]}.


makeコマンドにてCowboyと依存関係のパッケージを一括ダウンロードし、コンパイルする
$ make
$ tree --charset=o -L 2
.

-- Makefile
-- _rel
`-- hello_erlang_release
-- deps
-- cowboy
-- cowlib
`-- ranch
-- ebin
-- hello_erlang.app
-- hello_erlang_app.beam
`-- hello_erlang_sup.beam
-- erlang.mk
-- rel
-- sys.config
`-- vm.args
-- relx
-- relx.config

`-- src
|-- hello_erlang.app.src
|-- hello_erlang_app.erl
`-- hello_erlang_sup.erl


hello_handlerをcowboy_httpに合わせるために makeを実行
t=テンプレート名 n=モジュール名
$ make new t=cowboy_http n=hello_handler


生成された hello_handler.erl を変更し、httpの通信を行うようにする
$vim src/hello_handler.erl

handle(Req, State=#state{}) ->
{ok, Req2} = cowboy_req:reply(200,
[{<<"content-type">>, <<"text/plain">>}],
<<"Hello Erlang!">>,
Req),
{ok, Req2, State}.


ソースファイルをコンパイルして、実行する
$ make
$ make shell

1> application:ensure_all_started(hello_erlang).


http://localhost:8080 にアクセスして、Hello Erlang! が表示されれば成功です。


参考サイト
http://ninenines.eu/docs/en/cowboy/HEAD/guide/getting_started/
http://clina.jp/blog/cowboy-introduction.html