diff --git a/config/config.exs b/config/config.exs index 9188d79..0df80bc 100644 --- a/config/config.exs +++ b/config/config.exs @@ -2,5 +2,6 @@ import Config config :ha_handler, http_port: 4000, + acme_challenge_path: "acme-challenge", haproxy_socket: System.get_env("HAPROXY_SOCKET") || "/var/run/haproxy.sock" diff --git a/lib/ha_handler.ex b/lib/ha_handler.ex index a1d3b2e..e964080 100644 --- a/lib/ha_handler.ex +++ b/lib/ha_handler.ex @@ -3,4 +3,5 @@ defmodule HAHandler do def http_port, do: Application.get_env(:ha_handler, :http_port) def haproxy_socket, do: Application.get_env(:ha_handler, :haproxy_socket) + def acme_challenge_path, do: Application.get_env(:ha_handler, :acme_challenge_path) end diff --git a/lib/ha_handler/application.ex b/lib/ha_handler/application.ex index 27307b8..bb02cbf 100644 --- a/lib/ha_handler/application.ex +++ b/lib/ha_handler/application.ex @@ -10,7 +10,7 @@ defmodule HAHandler.Application do @impl true def start(_type, _args) do children = [ - {Plug.Cowboy, scheme: :http, plug: HAHandler.Web, options: [port: http_port()]} + {Plug.Cowboy, scheme: :http, plug: HAHandler.Web.Router, options: [port: http_port()]} ] # See https://hexdocs.pm/elixir/Supervisor.html diff --git a/lib/ha_handler/web.ex b/lib/ha_handler/web/controller.ex similarity index 76% rename from lib/ha_handler/web.ex rename to lib/ha_handler/web/controller.ex index 88f3f56..9059106 100644 --- a/lib/ha_handler/web.ex +++ b/lib/ha_handler/web/controller.ex @@ -1,13 +1,9 @@ -defmodule HAHandler.Web do +defmodule HAHandler.Web.Controller do import Plug.Conn alias HAHandler.HAProxy - def init(opts) do - opts - end - - def call(conn, _opts) do + def index(conn) do {:ok, hostname} = :inet.gethostname() stats = HAProxy.get_stats() diff --git a/lib/ha_handler/web/router.ex b/lib/ha_handler/web/router.ex new file mode 100644 index 0000000..f5fe15e --- /dev/null +++ b/lib/ha_handler/web/router.ex @@ -0,0 +1,35 @@ +defmodule HAHandler.Web.Router do + @moduledoc """ + This module dispatch incoming HTTP requests to their + related logic. Please refer to [1] for details. + + [1] https://hexdocs.pm/plug/Plug.Router.html#content + """ + + use Plug.Router + + import HAHandler, only: [acme_challenge_path: 0] + + alias HAHandler.Web.Controller + + # Note for plugs: oder is important, as a plug may stop + # want to stop the pipeline! + + plug Plug.Logger, log: :debug + # Note: `plug` is a macro, hence evaluated at + # compile-time. The configuration (which path to + # serve) cannot be modified at runtime with this + # system. + plug Plug.Static, + at: "/.well-known/acme-challenge/", + from: acme_challenge_path() + + plug :match + plug :dispatch + + get "/", do: Controller.index(conn) + + match _ do + send_resp(conn, 404, "Not found") + end +end