Skip to content

Instantly share code, notes, and snippets.

@abitdodgy
Last active May 11, 2016 20:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abitdodgy/2d35fb0d7c2ef31d8029a902b9514b26 to your computer and use it in GitHub Desktop.
Save abitdodgy/2d35fb0d7c2ef31d8029a902b9514b26 to your computer and use it in GitHub Desktop.
defmodule Event.Plug.API.VersionRouter do
import Plug.Conn
@default_version 1
def init(options) do
for {version, router} <- options, into: %{} do
{version, {router, router.init([])}}
end
end
def call(conn, options) do
version = get_version_from_conn(conn)
{router, router_options} = Map.fetch!(options, version)
router.call(conn, router_options)
end
defp get_version_from_conn(conn) do
version = case Plug.Conn.get_req_header(conn, "accept") do
[value | _] ->
Regex.run ~r/version=(\d)/, value, capture: :all_but_first
_ ->
@default_version
end
:"v#{version}"
end
end
defmodule Event.API.V1.Router do
use Event.Web, :router
pipeline :api do
plug :accepts, ["json"]
end
scope "/", alias: Event.API, host: "api." do
pipe_through :api
scope "/", alias: V1 do
resources "groups", GroupController
get "/", GroupController, :index
end
end
end
defmodule Event.API.V2.Router do
use Event.Web, :router
pipeline :api do
plug :accepts, ["json"]
end
scope "/", alias: Event.API, host: "api." do
pipe_through :api
scope "/", alias: V2 do
resources "groups", GroupController
get "/", GroupController, :index
end
end
end
defmodule Event.Router do
use Event.Web, :router
pipeline :browser do
plug :accepts, ["html"]
plug :fetch_session
plug :fetch_flash
plug :protect_from_forgery
plug :put_secure_browser_headers
end
pipeline :api do
plug Event.Plug.API.VersionRouter, v1: Event.API.V1.Router, v2: Event.API.V2.Router
plug :accepts, ["json"]
end
scope "/", Event, host: "api." do
pipe_through :api
get "/", PagesController, :index # redundant, but app wont work without it
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment