PlugMaintenance
An Elixir plug that returns a service unavailable response during maintenance.
Installation
-
Add
plug_maintenanceto your list of dependencies inmix.exs:
def deps do
[{:plug_maintenance, "~> 0.1.0"}]
end-
Ensure
plug_maintenanceis started before your application:
def application do
[applications: [:plug_maintenance]]
endUsage
- Add the Maintenance plug to the router.
pipeline :api do
plug :accepts, ["json"]
plug Maintenance
endscope "/" do
pipe_through :api
get "/v1/foo/bar, FooController, :bar
end-
By default, it checks whether the environment variable
MAINTENANCEistrueor whether there is a file namedmaintenanceand returns a service unavailable message with json, but if you want to customize it, please give your module for checking the maintenance status as an option.
plug Maintenance, monitor: {MyApp.MaintenanceMonitor, :check, []}, renderer: {MyApp.MaintenanceRenderer, :render, []}Custom monitor can be written like this.
defmodule MyApp.MaintenanceMonitor do
def check(conn, _opts) do
# Returning true will result in maintenance mode
# Write the logic for your environment
Redix.command(~w(GET maintenance)) == {:ok, "true"}
end
endFor Phoenix, renderer can be written like this.
defmodule MyApp.MaintenanceRenderer do
use MyApp.Web, :view
import Plug.Conn
def render(conn, _opts) do
conn
|> put_status(:service_unavailable)
|> put_view(__MODULE__)
|> render("index.html", layout: {MyApp.LayoutView, "maintenance.html"})
|> halt
end
end- If you want to limit the range to controller or action, add it to controller as follows.
plug Maintenanceplug Maintenance when action in [:index, :show:, :update]plug Maintenance, [monitor: {MyMonitor, :check, []}, renderer: {MyRenderer, :render, []}] when action in [:index, :show:, :update]