如何使用 elixir 自定义任务启动持久牛仔服务器

How to start persistent cowboy server using elixir custom task

我正在尝试使用 cowboy 和 plug 在 elixir 中构建一个非常简单的 Http 服务器。如果我 运行 iex -S mix 并且只要 iex 打开,它就可以正常工作。所以我决定创建一个自定义任务,它启动服务器但立即结束。我怎样才能坚持下去?我附上了我的 任务、应用程序和端点 文件以及这个问题。我将非常感谢任何解决方案。

server.exlib/mix/tasks/server.ex

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

endpoint.exlib/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.exlib/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 只显示 14:27:08.515 [info] Starting server at http://localhost:4000/ 然后我看到我的终端光标再次闪烁,我可以输入任何内容。

这里不需要自定义 mix 任务。 mix run 任务已提供您所需的一切。使用

mix run --no-halt