diff --git a/src/main/java/io/jare/tk/TkRelay.java b/src/main/java/io/jare/tk/TkRelay.java index 22f56a9..b2d6e3d 100644 --- a/src/main/java/io/jare/tk/TkRelay.java +++ b/src/main/java/io/jare/tk/TkRelay.java @@ -39,6 +39,7 @@ import org.takes.Take; import org.takes.rq.RqHref; import org.takes.rs.RsWithHeaders; +import org.takes.rs.RsWithoutHeader; import org.takes.tk.TkProxy; /** @@ -105,12 +106,34 @@ public Response act(final Request req) throws IOException { ); } final Domain domain = domains.next(); + return TkRelay.cached( + new RsWithHeaders( + new TkProxy(uri.toString()).act( + TkRelay.request(req, new Destination(uri).path()) + ), + String.format("X-Jare-Target: %s", uri), + String.format("X-Jare-Usage: %d", domain.usage().total()) + ) + ); + } + + /** + * Response that is cached forever. + * @param rsp Response + * @return New response + */ + private static Response cached(final Response rsp) { return new RsWithHeaders( - new TkProxy(uri.toString()).act( - TkRelay.request(req, new Destination(uri).path()) + new RsWithoutHeader( + new RsWithoutHeader( + new RsWithoutHeader(rsp, "Age"), + "Expires" + ), + "Cached-Control" ), - String.format("X-Jare-Target: %s", uri), - String.format("X-Jare-Usage: %d", domain.usage().total()) + "Age: 31536000", + "Cache-Control: max-age=31536000", + "Expires: Sun, 19 Jul 2020 18:06:32 GMT" ); } diff --git a/src/test/java/io/jare/tk/TkRelayTest.java b/src/test/java/io/jare/tk/TkRelayTest.java index a1c78d7..1d332e0 100644 --- a/src/test/java/io/jare/tk/TkRelayTest.java +++ b/src/test/java/io/jare/tk/TkRelayTest.java @@ -31,10 +31,12 @@ import org.takes.Take; import org.takes.facets.fork.FkRegex; import org.takes.facets.fork.TkFork; +import org.takes.facets.hamcrest.HmRsHeader; import org.takes.http.FtRemote; import org.takes.rq.RqFake; import org.takes.rs.RsPrint; import org.takes.tk.TkText; +import org.takes.tk.TkWithHeaders; /** * Test case for {@link TkRelay}. @@ -116,4 +118,38 @@ public void catchesInvalidUrls() throws Exception { ); } + /** + * TkRelay can set cache headers to "forever". + * @throws Exception If some problem inside + */ + @Test + public void setsCachingHeaders() throws Exception { + final Take target = new TkWithHeaders( + new TkText("cacheable forever"), + "Age: 600", + "Cache-control: max-age=600", + "Expires: Thu, 08 Dec 2016 22:51:37 GMT" + ); + new FtRemote(target).exec( + home -> MatcherAssert.assertThat( + new RsPrint( + new TkRelay(new FkBase()).act( + new RqFake( + Arrays.asList( + String.format("GET /?u=%s&whatever", home), + "Host: test.jare.io" + ), + "" + ) + ) + ), + Matchers.allOf( + new HmRsHeader("Age", "31536000"), + new HmRsHeader("Cache-Control", "max-age=31536000"), + new HmRsHeader("Expires", "Sun, 19 Jul 2020 18:06:32 GMT") + ) + ) + ); + } + }