この記事について
素の状態からcowboyでhello worldを返させるまでのメモ。
環境構築
環境構築は都度やっているとハマりそうなのでvagrantを使用。
https://github.com/lau/vagrant_elixir
ベース部分の作成
mix new —sup hello_world
を実行。
これによって、cowboyを載せるための土台が作成される。
cowboyを導入
cowboyを使うことを明示するため、mix.exのapplicatio関数とdeps関数を下記のように書き換え。
application
def application do
[applications: [:logger, :cowboy], # ← `:cowboy`を追記
mod: {HelloWorld, []}]
end
deps
defp deps do
[
{:cowboy, github: "ninenines/cowboy"}, # ← 追記
]
end
mix deps.get
を実行し、
ハンドラを追加
実際にアクセスした時に、どのようなものを返すかを定義するhandlerを追加。
ここではplain-textを返すようにする。
cowboy-trial/lib/hello_world/handlers/hello_world_handlers.ex
を追加し下記のように編集。
hello_world_handlers.ex
defmodule HelloWorld.Handlers.HelloWorld do
def init(req, opts) do
req2 = :cowboy_req.reply 200, %{"content-type" => "text/plain"}, "Hello World", req
{:ok, req2, opts}
end
end
ルーティング追加
cowboy-trial/lib/hello_world.ex
を編集する
hello-world.ex
defmodule HelloWorld do
def start(_type, _args) do
import Supervisor.Spec, warn: false
dispatch = :cowboy_router.compile routes
{:ok, _} = :cowboy.start_clear :http, 100, [{:port, 4000}], %{:env => %{:dispatch => dispatch}}
children = [
]
opts = [strategy: :one_for_one, name: HelloWorld.Supervisor]
Supervisor.start_link(children, opts)
end
defp routes do
[
{
:_,
[ {"/hello-world", HelloWorld.Handlers.HelloWorld, []} ]
}
]
end
def hello do
:world
end
end
起動して確認
下記コマンドで起動。
http://localhost:4000
にアクセスしてHello World
と出力しているかを確認する。
参考
cowboy2とectoでRESTサーバ - Qiita
ElixirからCowboy 2.0を使ってみる Part 1 - Qiita