Playing With Fire

Exploring the web one Elixir at a time

eWebmachine 2 - Hello World

Ewebmachine 2 has now been out a little while. This version is a complete rewrite of the project that breaks backward compatibility. Ewebmachine 1 was a wrapper around basho webmachine, whereas Ewebmachine is now a full re-implementation using a new DSL and Plugs.

Because it is different, I thought that I would create a simple HelloWorld just to explore the changes…

First off, lets create a new Mix project and go into that directory:

$> mix new helloworld
$> cd helloworld

In the project, we now need to add our dependencies, ewebmachine and cowboy, and add the reference to our supervisor module, so edit the mix.exs file as follows:

defmodule Helloworld.Mixfile do
  use Mix.Project

  def project do
    [app: :helloworld,
     version: "0.0.1",
     elixir: "~> 1.0",
     deps: deps]
  end

  def application do
    [applications: [:logger, :ewebmachine, :cowboy],
    mod: {HelloWorldSup,[]}]
  end

  defp deps do
    [{:ewebmachine, "2.0.5"}, {:cowboy, "~> 1.0"}]
  end
end

With these in place we can now run

$> mix deps.get

to fetch the dependencies.

With the dependencies in place, we can now build the supervisor module: lib/helloworldsup.ex

defmodule HelloWorldSup do
  use Application
  def start(_type, _args), do: Supervisor.start_link([Plug.Adapters.Cowboy.child_spec(:http, HelloWorld, [], port: 4000)], strategy: :one_for_one)
end

As you can see, this starts Cowboy against port 4000, serving the HelloWorld module, which we will build next.

Create the following file: lib/helloworld.ex

defmodule HelloWorld do
  use Ewebmachine.Builder.Resources
  if Mix.env == :dev, do: plug Ewebmachine.Plug.Debug
  resources_plugs error_forwarding: "/error/:status", nomatch_404: true

  resource "/" do %{} after
    content_types_provided do: ['text/html': :to_html]
    defh to_html, do: '<h1>Hello world</h1>'
  end
end

With this in place, you can now run:

$> iex -S mix

The application will compile and then you can point your web browser at http://localhost:4000, and you will see ‘Hello world’ staring back at you in large bold print.

I’ll explore the changes in greater detail in a different post.

Cheers