Created
May 13, 2016 11:54
-
-
Save abitdodgy/475c51f6604fba23bdeb03ca75bef547 to your computer and use it in GitHub Desktop.
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 Event.Plug.API.VersionRouter do | |
import Plug.Conn | |
@default_version 1 | |
def init(options) do | |
case Keyword.fetch!(options, :versions) do | |
versions -> | |
for {version, router} <- versions, into: %{} do | |
{version, {router, router.init([])}} | |
end | |
_ -> | |
options | |
end | |
end | |
def call(conn, options) do | |
case Map.fetch!(options, get_api_version_from_conn(conn)) do | |
{router, router_options} -> | |
router.call(conn, router_options) | |
_ -> | |
{router, router_options} = Map.fetch!(options, :default) | |
router.call(conn, router_options) | |
end | |
end | |
defp get_api_version_from_conn(conn) do | |
case get_accept_header(conn) do | |
[header | _] -> | |
case get_version_from_accept_header(header) do | |
[version | _] when byte_size(version) > 0 -> | |
{version, _} = Integer.parse(version) | |
version | |
_ -> | |
@default_version | |
end | |
_ -> | |
@default_version | |
end | |
end | |
defp get_accept_header(conn) do | |
Plug.Conn.get_req_header(conn, "accept") | |
end | |
defp get_version_from_accept_header([header | _]) do | |
Regex.run(~r/version=(\d)/, header, capture: :all_but_first) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment