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

Merge pull request #25 from jwinter/deflate

Add /deflate support for deflate-encoded data
This commit is contained in:
Eduardo Gurgel 2016-12-06 08:54:04 +13:00 committed by GitHub
commit 4969347c45
3 changed files with 58 additions and 0 deletions

View file

@ -17,6 +17,7 @@ defmodule HTTParrot do
{'/put', HTTParrot.PHandler, []},
{'/patch', HTTParrot.PHandler, []},
{'/delete', HTTParrot.DeleteHandler, []},
{'/deflate', HTTParrot.DeflateHandler, []},
{'/gzip', HTTParrot.GzipHandler, []},
{'/status/:code', [code: :int], HTTParrot.StatusCodeHandler, []},
{'/redirect/:n', HTTParrot.RedirectHandler, []},

View file

@ -0,0 +1,27 @@
defmodule HTTParrot.DeflateHandler do
@moduledoc """
Encode body using deflate encoding
"""
alias HTTParrot.GeneralRequestInfo
use HTTParrot.Cowboy, methods: ~w(GET HEAD OPTIONS)
def content_types_provided(req, state) do
{[{{"application", "json", []}, :get_json}], req, state}
end
def get_json(req, state) do
zlib = :zlib.open
:zlib.deflateInit(zlib)
{info, req} = GeneralRequestInfo.retrieve(req)
req = :cowboy_req.set_resp_header("content-encoding", "deflate", req)
json = response(info) |> JSX.prettify!
response = :zlib.deflate(zlib, json, :finish)
:zlib.deflateEnd(zlib)
{response, req, state}
end
defp response(info) do
info |> JSX.encode!
end
end

View file

@ -0,0 +1,30 @@
defmodule HTTParrot.DeflateHandlerTest do
use ExUnit.Case
import :meck
import HTTParrot.DeflateHandler
setup do
new HTTParrot.GeneralRequestInfo
new JSX
on_exit fn -> unload end
:ok
end
test "returns prettified json with query values, headers, url and origin" do
expect(HTTParrot.GeneralRequestInfo, :retrieve, 1, {:info, :req2})
expect(JSX, :encode!, [{[:info], :json}])
expect(JSX, :prettify!, [{[:json], "json"}])
expect(:cowboy_req, :set_resp_header, 3, :req3)
opened_zlib = :zlib.open
:zlib.deflateInit(opened_zlib)
body = :zlib.deflate(opened_zlib, "json", :finish)
:zlib.deflateEnd(opened_zlib)
assert get_json(:req1, :state) == {body, :req3, :state}
assert validate HTTParrot.GeneralRequestInfo
assert validate JSX
assert validate :cowboy_req
end
end