Elixir foundationSort Order

Elixir: Setup Plug and Cowboy - [004]

We'll setup our project to accept web requests. This might feel like we're jumping the gun, but it's ok, we need to work from something we understand then we will have ideas about where to go next. In this episode we show you how to setup plug and cowboy in our project

Installing Dependencies

Let's begin by modifying our mix.exs file

# ...# in the deps sectiondefp deps do  [    # Web Request    {:cowboy, "~> 2.4.0"},    {:plug, "~> 1.6"},  ]end

Now let's run mix deps.get to install the dependencies

Setting up the Supervision Tree

Now we'll need to setup the supervision tree in lib/botiful/application.ex to boot up our plug router. We'll use the new child spec style.

# ...# in the start functiondef start(_type, _args) do  # List all child processes to be supervised  children = [    {Plug.Adapters.Cowboy2, scheme: :http, plug: Botiful, options: [port: 8080]}    # Starts a worker by calling: Botiful.Worker.start_link(arg)    # {Botiful.Worker, arg},  ]  # ...end

Hello World Plug.Router

Now that we have the basic application setup let's write some code head over to lib/botiful.ex

defmodule Botiful do  @moduledoc """  Documentation for Botiful.  """  use Plug.Router  plug Plug.Static,    at: "/",    from: {:botiful, "priv/static"},    only: ~w(index.html)  plug :match  plug :dispatch  get "/hello" do    send_resp(conn, :ok, "world")  end  match(_, do: send_resp(conn, :not_found, "oh no"))end

We can now boot up our application via iex -S mix and browse to localhost:8080/hello in the browser. We should see world as a response on the page.