Khubaib Ahmad
Khubaib Ahmad

Reputation: 49

How to start persistent cowboy server using elixir custom task

I am trying to build a very simple Http server in the elixir using cowboy and plug. It works fine if I run iex -S mix and as long as iex is opened. So I decided to create a custom task and it starts the server but ends it immediately. How can I make persistent? I am attaching my task, application and endpoint file along with this question. I will be really thankful to any solution.

server.ex in lib/mix/tasks/server.ex

defmodule Mix.Tasks.MinimalServer.Server do
   use Mix.Task
   def run(_) do
      MinimalServer.Application.start("","")
   end
end

endpoint.ex in lib/MinimalServer/endpoint.ex

defmodule MinimalServer.Endpoint do
  use Plug.Router
  use Plug.Debugger
  use Plug.ErrorHandler

  alias MinimalServer.Router
  alias Plug.{HTML, Cowboy}

  require Logger

  plug(Plug.Logger, log: :debug)
  plug(:match)

  plug(Plug.Parsers,
    parsers: [:json],
    pass: ["application/json"],
    json_decoder: Poison
  )

  plug(:dispatch)

  def child_spec(opts) do
    %{
      id: __MODULE__,
      start: {__MODULE__, :start_link, [opts]}
    }
  end

  def start_link(_opts) do
    with {:ok, [port: port] = config} <- config() do
      Logger.info("Starting server at http://localhost:#{port}/")
      Cowboy.http(__MODULE__, [], config)
    end
  end

  forward("/bot", to: Router)

  match _ do
    conn
    |> put_resp_header("location", redirect_url())
    |> put_resp_content_type("text/html")
    |> send_resp(302, redirect_body())
  end

  defp redirect_body do
    ~S(<html><body>You are being <a href=")
    |> Kernel.<>(HTML.html_escape(redirect_url()))
    |> Kernel.<>(~S(">redirected</a>.</body></html>))
  end

  defp config, do: Application.fetch_env(:minimal_server, __MODULE__)
  defp redirect_url, do: Application.get_env(:minimal_server, :redirect_url)

  def handle_errors(%{status: status} = conn, %{kind: _kind, reason: _reason, stack: _stack}),
    do: send_resp(conn, status, "Something went wrong")
end

application.ex in lib/MinimalServer/application.ex

defmodule MinimalServer.Application do
  use Application

  alias MinimalServer.Endpoint

  def start(_type, _args),
    do: Supervisor.start_link(children(), opts())

  defp children do
    [
      Endpoint
    ]
  end

  defp opts do
    [
      strategy: :one_for_one,
      name: MinimalServer.Supervisor
    ]
  end
end

mix minimal_server.server only shows 14:27:08.515 [info] Starting server at http://localhost:4000/ and then I see my terminal cursor blinking again and I could type anything.

Upvotes: 0

Views: 147

Answers (1)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121010

You don’t need a custom mix task here. All you need is already provided by mix run task. Use

mix run --no-halt

Upvotes: 1

Related Questions