From 616e7779e071728add3ca282922d295a06efb51b Mon Sep 17 00:00:00 2001 From: Toshiaki Maki Date: Fri, 10 Feb 2023 23:07:31 +0900 Subject: [PATCH] Add RFC-8246 support to CacheControl This commit adds the "immutable" Cache-Control directives in `CacheControl`. Closes gh-29955 --- .../org/springframework/http/CacheControl.java | 17 +++++++++++++++++ .../springframework/http/CacheControlTests.java | 6 ++++++ 2 files changed, 23 insertions(+) diff --git a/spring-web/src/main/java/org/springframework/http/CacheControl.java b/spring-web/src/main/java/org/springframework/http/CacheControl.java index 29366576501..a78ed947d54 100644 --- a/spring-web/src/main/java/org/springframework/http/CacheControl.java +++ b/spring-web/src/main/java/org/springframework/http/CacheControl.java @@ -77,6 +77,8 @@ public class CacheControl { @Nullable private Duration sMaxAge; + private boolean immutable = false; + /** * Create an empty CacheControl instance. @@ -320,6 +322,18 @@ public class CacheControl { return this; } + /** + * Add an "immutable" directive. + *

This directive indicates that the origin server will not update the + * representation of that resource during the freshness lifetime of the response. + * @return {@code this}, to facilitate method chaining + * @see rfc8246 + */ + public CacheControl immutable() { + this.immutable = true; + return this; + } + /** * Return the "Cache-Control" header value, if any. * @return the header value, or {@code null} if no directive was added @@ -369,6 +383,9 @@ public class CacheControl { if (this.staleWhileRevalidate != null) { appendDirective(headerValue, "stale-while-revalidate=" + this.staleWhileRevalidate.getSeconds()); } + if (this.immutable) { + appendDirective(headerValue, "immutable"); + } return headerValue.toString(); } diff --git a/spring-web/src/test/java/org/springframework/http/CacheControlTests.java b/spring-web/src/test/java/org/springframework/http/CacheControlTests.java index 6da839902b2..8dfdf91406c 100644 --- a/spring-web/src/test/java/org/springframework/http/CacheControlTests.java +++ b/spring-web/src/test/java/org/springframework/http/CacheControlTests.java @@ -101,4 +101,10 @@ public class CacheControlTests { assertThat(cc.getHeaderValue()).isEqualTo("max-age=3600, stale-while-revalidate=7200"); } + @Test + public void immutable() throws Exception { + CacheControl cc = CacheControl.maxAge(Duration.ofHours(1)).immutable(); + assertThat(cc.getHeaderValue()).isEqualTo("max-age=3600, immutable"); + } + }