Skip to content

Commit

Permalink
#25 cache forever
Browse files Browse the repository at this point in the history
  • Loading branch information
yegor256 committed Dec 9, 2016
1 parent 25da6da commit 902a5cc
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 4 deletions.
31 changes: 27 additions & 4 deletions src/main/java/io/jare/tk/TkRelay.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;

/**
Expand Down Expand Up @@ -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"
);
}

Expand Down
36 changes: 36 additions & 0 deletions src/test/java/io/jare/tk/TkRelayTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -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}.
Expand Down Expand Up @@ -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")
)
)
);
}

}

0 comments on commit 902a5cc

Please sign in to comment.