3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ElixirAdvent Calendar 2016

Day 20

ElixirでCowboy2を使ってhello world

Posted at

Elixir、Cowboy2でhello worldを出力するところまでです。

Cowboy1系と書き方が変わってたり、ネットでサンプルみてもうまくいかなかったので
どこらへんの書き方が違ったかまとめていきたいと思います。

##mix.exs

#Cowboy1
defp deps do
  [{:cowboy, "~> 1.0"}]
end

#Cowboy2
defp deps do
  [{:cowboy, github: "ninenines/cowboy"}]
end

##cowboy1.ex

defmodule Cowboy1 do
 use Application

  def start(_type, _args) do
    import Supervisor.Spec, warn: false

    dispatch = :cowboy_router.compile routes
    {:ok, _} = :cowboy.start_http :http, 100, [{:port, 3000}], [{:env, [{:dispatch, dispatch}]}]

    children = [
    ]

    opts = [strategy: :one_for_one, name: Cowboy1.Supervisor]
    Supervisor.start_link(children, opts)
  end

  defp routes do
    [
      {:_, [
            {"/", Cowboy1.Handlers.Hello, []},
          ]
      }
    ]
  end
end

##cowboy2.ex

defmodule Cowboy2 do
 use Application

  def start(_type, _args) do
    import Supervisor.Spec, warn: false

    dispatch = :cowboy_router.compile routes
    {:ok, _} = :cowboy.start_clear(:http, 100, [{:port, 3000}], %{:env => %{:dispatch => dispatch}}) ←ここの書き方が変わった

    children = [
    ]

    opts = [strategy: :one_for_one, name: Cowboy2.Supervisor]
    Supervisor.start_link(children, opts)
  end

  defp routes do
    [
      {:_, [
            {"/[:id]", Cowboy2.Handlers.Hello, []}
          ]
      }
    ]
  end
end

##hello.ex

#Cowboy1
defmodule Cowboy1.Handlers.Hello do

  def init(_type, req, []) do
    {:ok, req, :no_state}
  end

  def handle(req, state) do
    {:ok, reply} = :cowboy_req.reply 200, [{"content-type", "text/plain"}], "hello world, cowboy1", req
    {:ok, reply, state}
  end

  def terminate(_, _, _), do: :ok

end

#Cowboy2
defmodule Cowboy2.Handlers.Hello do

  def init(req, state) do ← initのパラメータが変わった
    handle(req, state) ← 1系はinitのあとにhandleが呼ばれていたみたいが2系は呼ばれないみたい
  end

  def handle(req, state) do
    {:ok, req} = :cowboy_req.reply( 200, %{"content-type" => "text/plain"}, "hello world, cowboy2", req) ←2番目の引数がMapになった
    {:ok, req, state}
  end

  def terminate(_, _, _), do: :ok

end

たいした内容ではないですがサンプルのソースはgithubに置いてあります。

3
1
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
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?