1
0
Fork 0
mirror of https://github.com/edgurgel/httparrot synced 2025-04-05 08:12:31 -04:00

Add '/base64/:value'

This commit is contained in:
Eduardo Gurgel 2014-01-22 13:45:39 -03:00
parent dcae8a3221
commit ea35bc4c5a
3 changed files with 61 additions and 1 deletions

View file

@ -22,7 +22,8 @@ defmodule HTTParrot do
{'/stream/:n', HTTParrot.StreamHandler, []},
{'/delay/:n', HTTParrot.DelayedHandler, []},
{'/html', :cowboy_static, {:priv_file, :httparrot, "html.html"}},
{'/deny', HTTParrot.DenyHandler, []} ] }
{'/deny', HTTParrot.DenyHandler, []},
{'/base64/:value', HTTParrot.Base64Handler, []} ] }
])
{:ok, http_port} = :application.get_env(:httparrot, :http_port)
{:ok, https_port} = :application.get_env(:httparrot, :https_port)

View file

@ -0,0 +1,38 @@
defmodule HTTParrot.Base64Handler do
@moduledoc """
Returns urlsafe base64 decoded data.
"""
def init(_transport, _req, _opts) do
{:upgrade, :protocol, :cowboy_rest}
end
def allowed_methods(req, state) do
{["GET", "HEAD", "OPTIONS"], req, state}
end
def content_types_provided(req, state) do
{[{{"application", "octet-stream", []}, :get_binary}], req, state}
end
def get_binary(req, state) do
{value, req} = :cowboy_req.binding(:value, req)
value = decode(value)
{value, req, state}
end
defp decode(bin) when is_binary(bin) do
bin = case rem(byte_size(bin), 4) do
2 -> << bin :: binary, "==" >>
3 -> << bin :: binary, "=" >>
_ -> bin
end
bc <<x>> inbits :base64.decode(bin), x != ?=, do: <<urldecode_digit(x)>>
end
defp urldecode_digit(?_), do: ?/
defp urldecode_digit(?-), do: ?+
defp urldecode_digit(d), do: d
def terminate(_, _, _), do: :ok
end

View file

@ -0,0 +1,21 @@
defmodule HTTParrot.Base64HandlerTest do
use ExUnit.Case
import :meck
import HTTParrot.Base64Handler
setup do
new :cowboy_req
end
teardown do
unload :cowboy_req
end
test "returns decoded base64 urlsafe" do
expect(:cowboy_req, :binding, [{[:value, :req1], {"LytiYXNlNjQrLw", :req2}}])
assert get_binary(:req1, :state) == { "/+base64+/", :req2, :state}
assert validate :cowboy_req
end
end