Creating a minimal Plug based http server in an exs file

I am trying to create a quick n dirty http server in an exs file that only sends the string ‘Hello World’. Currently it’s

Mix.install([{:plug_cowboy, "~> 2.0"}])    

defmodule HWPlug.Plug do
  import Plug.Conn    

  def init(options), do: options    

  def call(conn, _opts) do
    conn
    |> put_resp_content_type("text/plain")
    |> send_resp(200, "Hello World!\n")
  end
end    

defmodule HWApp.Application do
  use Application
  require Logger    

  def start(_type, _args) do
    children = [
      {Plug.Cowboy, scheme: :http, plug: HWPlug.Plug, options: [port: 8080]}
    ]    

    opts = [strategy: :one_for_one, name: HWApp.Supervisor]    

    Logger.info("Starting application...")    

    Supervisor.start_link(children, opts)
  end
end    

Application.start(HWApp.Application)

But this does not work. I’m not able to execute this like elixir server.exs . How can I create a minimal http server without setting up a mix project?

1 Like

Application.start returns once your application is started, then the script is done and terminates.

You can look at this one about how to get around the “reaching the end and terminate”: mix_install_examples/bandit.exs at main · wojtekmach/mix_install_examples · GitHub

2 Likes

Answering my own question… What I was looking for was

Mix.install([{:plug_cowboy, "~> 2.0"}])

defmodule HWPlug.Plug do
  import Plug.Conn

  def init(options), do: options

  def call(conn, _opts) do
    conn
    |> put_resp_content_type("text/plain")
    |> send_resp(200, "Hello World!\n")
  end
end

Plug.Adapters.Cowboy.http(HWPlug.Plug, [])

I can run this like elixir --no-halt server.exs.