Last active
December 12, 2017 05:06
-
-
Save FND/1b22ce5cabef52d95cb6 to your computer and use it in GitHub Desktop.
Phoenix content negotiation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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