diff --git a/lib/httparrot.ex b/lib/httparrot.ex index 72092dc..24da9dc 100644 --- a/lib/httparrot.ex +++ b/lib/httparrot.ex @@ -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, []}, diff --git a/lib/httparrot/deflate_handler.ex b/lib/httparrot/deflate_handler.ex new file mode 100644 index 0000000..3bcb0f2 --- /dev/null +++ b/lib/httparrot/deflate_handler.ex @@ -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 diff --git a/test/deflate_handler_test.exs b/test/deflate_handler_test.exs new file mode 100644 index 0000000..2be4bd5 --- /dev/null +++ b/test/deflate_handler_test.exs @@ -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