Support ETag generation on ResourceWebHandler

This commit replicates the ETag generation option now available on
`ResourceHttpRequestHandler` but for its WebFlux counterpart.

See gh-29031
This commit is contained in:
Brian Clozel
2023-10-25 16:01:15 +02:00
parent ff14c5121d
commit 9ac5eb0f55
2 changed files with 72 additions and 2 deletions

View File

@@ -27,6 +27,7 @@ import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@@ -123,6 +124,9 @@ public class ResourceWebHandler implements WebHandler, InitializingBean {
private boolean useLastModified = true;
@Nullable
private Function<Resource, String> etagGenerator;
private boolean optimizeLocations = false;
@@ -275,6 +279,29 @@ public class ResourceWebHandler implements WebHandler, InitializingBean {
return this.useLastModified;
}
/**
* Configure a generator function that will be used to create the ETag information,
* given a {@link Resource} that is about to be written to the response.
* <p>This function should return a String that will be used as an argument in
* {@link ServerWebExchange#checkNotModified(String)}, or {@code null} if no value
* can be generated for the given resource.
* @param etagGenerator the HTTP ETag generator function to use.
* @since 6.1
*/
public void setEtagGenerator(@Nullable Function<Resource, String> etagGenerator) {
this.etagGenerator = etagGenerator;
}
/**
* Return the HTTP ETag generator function to be used when serving resources.
* @return the HTTP ETag generator function
* @since 6.1
*/
@Nullable
public Function<Resource, String> getEtagGenerator() {
return this.etagGenerator;
}
/**
* Set whether to optimize the specified locations through an existence
* check on startup, filtering non-existing directories upfront so that
@@ -418,7 +445,9 @@ public class ResourceWebHandler implements WebHandler, InitializingBean {
}
// Header phase
if (isUseLastModified() && exchange.checkNotModified(Instant.ofEpochMilli(resource.lastModified()))) {
String eTagValue = (this.getEtagGenerator() != null) ? this.getEtagGenerator().apply(resource) : null;
Instant lastModified = isUseLastModified() ? Instant.ofEpochMilli(resource.lastModified()) : Instant.MIN;
if (exchange.checkNotModified(eTagValue, lastModified)) {
logger.trace(exchange.getLogPrefix() + "Resource not modified");
return Mono.empty();
}