Elli on Elixir
A complete guide to running the Elli web server in an Elixir application.
- Published
- Reading time
- 2 min read
This guide expands on the shorter answers I found while getting knutin/elli to work with Elixir. Those answers were correct, but I needed more detail before I could run Elli in a new Elixir project.
-
Implement a handler with
@behaviour :elli_handler.This module is the router and controller. A minimal implementation looks like this:
# lib/elli_handler.ex defmodule ElliHandler do @behaviour :elli_handler alias :elli_request, as: Request def handle(req, args) do handle(Request.method(req), Request.path(req), req, args) end def handle(:GET, _, req, args) do # do something with the request. # e.g. you can use Request.get_arg/2 to fetch a query param say = Request.get_arg("say", req) # Return a tuple with 3 elements # status code, list of header tuples, response body {200, [], "echo, #{say}"} end # React to events throughout the connection, request, and response cycle. # Elli evaluates the return value, so this callback must be implemented. def handle_event(event, args, config) do # Here would be a good point to handle logging. # IO.inspect([event, args, config]) :ok end end -
Create an application that starts an Elli supervisor.
# lib/elli_supervisor.ex defmodule ElliSupervisor do use Supervisor def start_link(ref, options) do Supervisor.start_link(__MODULE__, options, name: ref) end def init(options) do children = [ worker(:elli, [options], id: :elli_http_server) ] supervise(children, strategy: :one_for_one) end def shutdown(ref) do case Supervisor.terminate_child(ref, :elli_http_server) do :ok -> Supervisor.delete_child(ref, :elli_http_server) err -> err end end end # lib/app.ex defmodule App do use Application def start(_type, _args) do import Supervisor.Spec, warn: false # Start the Elli supervisor with its options. # The callback must implement the elli_handler behaviour. # The port controls where Elli listens and defaults to 8080. ElliSupervisor.start_link(__MODULE__, callback: ElliHandler, port: 3000) end end # in mix.exs def application do [ mod: {App, []} ] end -
Add Elli as a dependency in
mix.exs.Run
mix deps.getto install your dependencies. Start your server withmix run --no-haltor in a console usingiex -S mix.# in mix.exs defp deps do [ # elli is our web server layer {:elli, github: "knutin/elli"} ] end