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

Add '/cookies/set'

This commit is contained in:
Eduardo Gurgel 2014-01-02 00:06:57 -03:00
parent 5b4a5e52f9
commit f5698b9708
3 changed files with 56 additions and 0 deletions

View file

@ -11,6 +11,7 @@ defmodule HTTParrot do
{'/status/:code', HTTParrot.StatusCodeHandler, []},
{'/redirect-to', HTTParrot.RedirectToHandler, []},
{'/cookies', HTTParrot.CookiesHandler, []},
{'/cookies/set', HTTParrot.SetCookiesHandler, []},
{'/basic-auth/:user/:passwd', HTTParrot.BasicAuthHandler, []},
{'/html', :cowboy_static, {:priv_file, :httparrot, "html.html"}} ] }
])

View file

@ -0,0 +1,32 @@
defmodule HTTParrot.SetCookiesHandler do
def init(_transport, _req, _opts) do
{:upgrade, :protocol, :cowboy_rest}
end
def allowed_methods(req, state) do
{["GET"], req, state}
end
def malformed_request(req, state) do
{qs_vals, req} = :cowboy_req.qs_vals(req)
if Enum.empty?(qs_vals), do: {true, req, state}, else: {false, req, qs_vals}
end
def content_types_provided(req, state) do
{[{{"application", "json", []}, :get_json}], req, state}
end
def get_json(req, qs_vals) do
req = Enum.reduce qs_vals, req, fn({name, value}, req) ->
set_cookie(name, value, req)
end
{:ok, req} = :cowboy_req.reply(302, [{"location", "/cookies"}], "Redirecting...", req)
{:halt, req, qs_vals}
end
defp set_cookie(name, value, req) do
:cowboy_req.set_resp_cookie(name, value, [path: "/"], req)
end
def terminate(_, _, _), do: :ok
end

View file

@ -0,0 +1,23 @@
defmodule HTTParrot.SetCookiesHandlerTest do
use ExUnit.Case
import :meck
import HTTParrot.SetCookiesHandler
setup do
new :cowboy_req
end
teardown do
unload :cowboy_req
end
test "redirect to /cookies " do
expect(:cowboy_req, :set_resp_cookie, [{[:k1, :v1, [path: "/"], :req1], :req2},
{[:k2, :v2, [path: "/"], :req2], :req3}])
expect(:cowboy_req, :reply, [{[302, [{"location", "/cookies"}], "Redirecting...", :req3], {:ok, :req4}}])
assert get_json(:req1, [k1: :v1, k2: :v2]) == {:halt, :req4, [k1: :v1, k2: :v2]}
assert validate :cowboy_req
end
end