1
0
Fork 0
mirror of https://github.com/benbusby/farside.git synced 2025-04-19 18:38:42 +00:00
farside/lib/farside/router.ex
Ben Busby 56b9c52528
Display list of available instances on home page
This introduces a number of new changes:
- Services are now inserted into redis with a prefix prepended to the
key name. This allows for easier filtering to get only live instances.
- The home page now uses an eex template for displaying all live
instances for every service, determined by the last update
- A "last_updated" field was added
- farside.ex was added to contain all functionality related to querying
for instances (WIP)
- Other improvements
2021-11-08 17:08:19 -07:00

65 lines
1.3 KiB
Elixir

defmodule Farside.Router do
@index Application.fetch_env!(:farside, :index)
@fallback_str Application.fetch_env!(:farside, :fallback_str)
@service_prefix Application.fetch_env!(:farside, :service_prefix)
use Plug.Router
plug(:match)
plug(:dispatch)
get "/" do
resp =
EEx.eval_file(
@index,
last_updated: Farside.get_last_updated(),
services: Farside.get_services_map()
)
send_resp(conn, 200, resp)
end
get "/ping" do
# Useful for app healthcheck
{:ok, resp} = Redix.command(:redix, ["PING"])
send_resp(conn, 200, resp)
end
get "/:service/*glob" do
path = Enum.join(glob, "/")
{:ok, instances} =
Redix.command(
:redix,
[
"LRANGE",
"#{@service_prefix}#{service}",
"0",
"-1"
]
)
# Either pick a random available instance,
# or fall back to the default one
instance =
if Enum.count(instances) > 0 do
Enum.random(instances)
else
{:ok, result} =
Redix.command(
:redix,
["GET", "#{service}#{@fallback_str}"]
)
result
end
# Redirect to the available instance
conn
|> Plug.Conn.resp(:found, "")
|> Plug.Conn.put_resp_header(
"location",
"#{instance}/#{path}"
)
end
end