Simple elixir web server with plug
Simple elixir web server with plug
Everybody seems to use Phoenix for their web applications in Elixir. Sometimes,
however, you simply would like to take the easy route and write a small server
at a lower lever because you don’t need all the functionality provided by
Phoenix. It is a layer on top of erlang server Cowboy.
You can find the final app here at github: simple_plug.
Let’s start. First, create a new mix application with a supervisor:
mix new simple_plug --sup
Then add the plug and cowboy dependency into the mix.exs
file:
...
defp deps do
[
{:cowboy, "~> 1.0.0"},
{:plug, "~> 0.12"},
]
end
...
Run mix do deps.get, compile
to get and compile the dependencies.
We then need a starter for the plug server lib/plug_starter.ex
:
defmodule SimplePlug.Plugstarter do
def start_link() do
{:ok, _} = Plug.Adapters.Cowboy.http SimplePlug.Router, []
end
end
which is started through our supervisor at lib/simple_plug.ex
:
defmodule SimplePlug do
use Application
# See http://elixir-lang.org/docs/stable/elixir/Application.html
# for more information on OTP Applications
def start(_type, _args) do
import Supervisor.Spec, warn: false
children = [
# Define workers and child supervisors to be supervised
# worker(SimplePlug.Worker, [arg1, arg2, arg3])
worker(SimplePlug.Plugstarter, [])
]
# See http://elixir-lang.org/docs/stable/elixir/Supervisor.html
# for other strategies and supported options
opts = [strategy: :one_for_one, name: SimplePlug.Supervisor]
Supervisor.start_link(children, opts)
end
end
The last thing we need it the plug-router, which responds to the http request.
In our case we simply show back the entered parameters. If you enter
http://localhost:4000/?aaa=1234
it would return received %{"aaa" => "1234"}
.
If you use any other route, it returns a 404 page.
Paste the following code into lib/router.ex
:
defmodule SimplePlug.Router do
use Plug.Router
require Logger
# plug Plug.Logger
plug :match
plug :dispatch
def init(options) do
# initialize your options here
options
end
get "/" do
# Get the parameters
conn = fetch_query_params(conn)
send_resp(conn, 200, "received #{inspect(conn.params)}")
end
match _ do
IO.inspect(conn.params)
send_resp(conn, 404, "oops")
end
end
Now you can start the server with iex -S mix
and enjoy your lovely plug server at
http://localhost:4000/
.