From eb05eeb442614783631d9cee97c3949efff5803e Mon Sep 17 00:00:00 2001 From: Max Kuzmins Date: Thu, 5 Sep 2019 09:38:58 +0100 Subject: [PATCH 1/3] Add Maru.Response.json_gzipped/2. --- lib/maru/response.ex | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/lib/maru/response.ex b/lib/maru/response.ex index dad48c0..62972d4 100644 --- a/lib/maru/response.ex +++ b/lib/maru/response.ex @@ -48,6 +48,23 @@ defmodule Maru.Response do |> Plug.Conn.halt() end + @doc """ + Make gzipped json format response. + """ + def json_gzipped(%Plug.Conn{} = conn, data) do + json_library = Maru.json_library() + + gzipped = data + |> json_library.encode_to_iodata! + |> :zlib.gzip + + conn + |> Plug.Conn.put_resp_content_type("application/json") + |> Plug.Conn.put_resp_header("content-encoding", "gzip") + |> Plug.Conn.send_resp(conn.status || 200, gzipped) + |> Plug.Conn.halt() + end + @doc """ Make html format response. """ From 655ccc7de10f90f572e03d7e8edd04cc58719a33 Mon Sep 17 00:00:00 2001 From: Max Kuzmins Date: Thu, 5 Sep 2019 10:25:23 +0100 Subject: [PATCH 2/3] Maru.Test.json_response/1 to check content-encoding. --- lib/maru/test.ex | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/lib/maru/test.ex b/lib/maru/test.ex index aceacf6..f839d05 100644 --- a/lib/maru/test.ex +++ b/lib/maru/test.ex @@ -95,6 +95,13 @@ defmodule Maru.Test do Get response from conn as json. """ def json_response(conn) do - Jason.decode!(conn.resp_body) + case Plug.Conn.get_resp_header(conn, "content-encoding") do + ["gzip"] -> + conn.resp_body + |> :zlib.gunzip + |> Jason.decode! + [] -> + Jason.decode!(conn.resp_body) + end end end From 2d5b854262fbaecbec1ea07fa62519d8b0938f8e Mon Sep 17 00:00:00 2001 From: Max Kuzmins Date: Thu, 5 Sep 2019 10:25:59 +0100 Subject: [PATCH 3/3] Test gzipped JSON response. --- test/test_test.exs | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/test/test_test.exs b/test/test_test.exs index 4376ef8..56906bd 100644 --- a/test/test_test.exs +++ b/test/test_test.exs @@ -117,21 +117,38 @@ defmodule Maru.TestTest do post do json(conn, params) end + + params do + requires :foo + end + + put do + json_gzipped(conn, params) + end end defmodule TestTest3 do use Maru.Test, server: Maru.TestTest.TestServer3 - def test do + def test_post do build_conn() |> Plug.Conn.put_req_header("content-type", "application/json") |> put_body_or_params(~s({"foo":"bar"})) |> post("/") |> json_response end + + def test_put do + build_conn() + |> Plug.Conn.put_req_header("content-type", "application/json") + |> put_body_or_params(~s({"foo":"bar"})) + |> put("/") + |> json_response + end end - assert %{"foo" => "bar"} = TestTest3.test() + assert %{"foo" => "bar"} = TestTest3.test_post() + assert %{"foo" => "bar"} = TestTest3.test_put() end test "mounted" do