Gate (ex_gate v0.0.1)
Gate is a macro-based library that provides pipeline functionality similar to Phoenix's pipelines. It allows you to define reusable plug pipelines with conditional execution and use them in your Plug.Router.
Usage
defmodule MyApp.Router do
use Plug.Router
use Gate
gate :browser do
plug :put_resp_content_type, "text/html"
plug Plug.Logger
plug :auth_required
get "/" do
send_resp(conn, 200, "Welcome to the homepage")
end
end
gate :api do
plug :put_resp_content_type, "application/json"
plug Plug.Logger
get "/api" do
send_resp(conn, 200, ~s({"message": "Welcome to the API"}))
end
end
match _ do
send_resp(conn, 404, "Oops!")
end
defp put_resp_content_type(conn, type) do
Plug.Conn.put_resp_content_type(conn, type)
end
defp auth_required(conn) do
if get_req_header(conn, "authorization") == ["Bearer valid_token"] do
true
else
Plug.Conn.send_resp(conn, 401, "Unauthorized")
false
end
end
end
Summary
Functions
Defines a pipeline of plugs with an optional name.
Defines a GET route within the current pipeline.
Adds a plug to the current pipeline. Optionally accepts a list of conditions that must be met for the plug to be applied.
Functions
Defines a pipeline of plugs with an optional name.
Example
gate :browser do
plug :put_resp_content_type, "text/html"
plug Plug.Logger
end
Defines a GET route within the current pipeline.
Example
get "/" do
send_resp(conn, 200, "Welcome to the homepage")
end
Adds a plug to the current pipeline. Optionally accepts a list of conditions that must be met for the plug to be applied.
Example
plug :put_resp_content_type, "text/html"
plug Plug.Logger, []
plug MyAuthPlug, [], [auth_required: true]