LoginSignup
1
0

More than 5 years have passed since last update.

CowboyのHelloWorldまで

Last updated at Posted at 2017-04-13

この記事について

素の状態から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

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0