Plug Examples
Jump to navigation
Jump to search
Plug Examples[edit]
Basic Plug Example[edit]
defmodule MyApp.HelloWorld do @behaviour Plug def init(options), do: options def call(conn, _opts) do conn |> put_resp_content_type("text/plain") |> send_resp(200, "Hello, world!") end end
Redirecting Plug Example[edit]
defmodule MyApp.Redirect do @behaviour Plug def init(options), do: options def call(conn, _opts) do conn |> put_resp_content_type("text/html") |> put_resp_header("location", "https://elixir-lang.org") |> send_resp(301, "") end end
Logging Plug Example[edit]
defmodule MyApp.Logger do @behaviour Plug def init(options), do: options def call(conn, _opts) do conn |> IO.inspect(label: "Request") |> Plug.Conn.forward(conn) |> IO.inspect(label: "Response") end end
Authentication Plug Example[edit]
defmodule MyApp.Authenticate do @behaviour Plug def init(options), do: options def call(conn, _opts) do case Plug.Conn.get_req_header(conn, "authorization") do nil -> send_unauthorized(conn) "Bearer " <> token -> case authenticate(token) do {:ok, _user} -> Plug.Conn.forward(conn) {:error, _reason} -> send_unauthorized(conn) end _ -> send_unauthorized(conn) end end defp send_unauthorized(conn) do conn |> put_resp_content_type("text/plain") |> send_resp(401, "Unauthorized") end defp authenticate(token) do # Your authentication logic here end end
Routing Plug Example[edit]
defmodule MyApp.Router do @behaviour Plug.Router use Plug.Builder plug :match plug :dispatch get "/" do send_resp(conn, 200, "Hello, Elixir!") end match _ do send_resp(conn, 404, "Route not found") end end
Database Query Plug Example[edit]
defmodule MyApp.DatabaseQuery do @behaviour Plug def init(options), do: options def call(conn, _opts) do query = Plug.Conn.get_query_params(conn) result = MyApp.Database.query(query) conn |> put_resp_content_type("text/plain") |> send_resp(200, "#{inspect(result)}") end end
Auth middleware composition[edit]
defmodule MyApp.AuthPipeline do use Plug.Builder plug MyApp.Authenticate plug MyApp.Logger plug MyApp.Router end