Search code examples
elixircowboyplug

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?


Solution

  • Actually, I found out that this does not need an Application simply

    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, [])
    

    works