Skip to content

Instantly share code, notes, and snippets.

@FND
Last active December 12, 2017 05:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save FND/1b22ce5cabef52d95cb6 to your computer and use it in GitHub Desktop.
Save FND/1b22ce5cabef52d95cb6 to your computer and use it in GitHub Desktop.
Phoenix content negotiation
defmodule ContentNegotiator do
def init(opts), do: opts
def call(conn, opts) do
conn
|> Phoenix.Controller.accepts(Map.keys(opts))
|> dispatch_by_accept(opts)
end
defp dispatch_by_accept(%Plug.Conn{halted: true} = conn, _), do: conn
defp dispatch_by_accept(conn, opts) do
plug = Map.fetch!(opts, conn.params["format"])
plug.call(conn, plug.init([]))
end
end
defmodule Sampler.Router do
defmodule HTMLPipeline do
use Plug.Builder
import Phoenix.Controller
plug :protect_from_forgery
end
defmodule JSONPipeline do
import Phoenix.Controller
# can't use `Plug.Builder` here as it expects at least one `plug`
def init(opts), do: opts
def call(conn, _), do: conn
end
use Sampler.Web, :router
pipeline :browser do
plug :fetch_session
plug :fetch_flash
plug ContentNegotiator, %{"html" => HTMLPipeline,
"json" => JSONPipeline}
end
scope "/", Sampler do
pipe_through :browser
get "/", PageController, :index
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment