mirror of
https://github.com/edgurgel/httparrot
synced 2025-04-05 08:12:31 -04:00
Add '/cookies/set'
This commit is contained in:
parent
5b4a5e52f9
commit
f5698b9708
3 changed files with 56 additions and 0 deletions
|
@ -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"}} ] }
|
||||
])
|
||||
|
|
32
lib/httparrot/set_cookies_handler.ex
Normal file
32
lib/httparrot/set_cookies_handler.ex
Normal 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
|
23
test/set_cookies_handler_test.exs
Normal file
23
test/set_cookies_handler_test.exs
Normal 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
|
Loading…
Add table
Reference in a new issue