1
0
Fork 0
mirror of https://github.com/edgurgel/httparrot synced 2025-04-17 20:14:10 -04:00
httparrot/lib/httparrot/redirect_handler.ex
2014-01-07 21:01:10 -03:00

34 lines
839 B
Elixir

defmodule HTTParrot.RedirectHandler do
@moduledoc """
Redirects to the foo URL.
"""
def init(_transport, _req, _opts) do
{:upgrade, :protocol, :cowboy_rest}
end
def allowed_methods(req, state) do
{["GET", "HEAD", "OPTIONS"], req, state}
end
def malformed_request(req, state) do
{n, req} = :cowboy_req.binding(:n, req)
try do
n = n |> binary_to_integer |> max(1)
{false, req, n}
rescue
ArgumentError -> {true, req, state}
end
end
def resource_exists(req, state), do: {false, req, state}
def previously_existed(req, state), do: {true, req, state}
def moved_temporarily(req, n) do
{host_url, req} = :cowboy_req.host_url(req)
url = if n > 1, do: "/redirect/#{n-1}", else: "/get"
{{true, host_url <> url}, req, nil}
end
def terminate(_, _, _), do: :ok
end