Фильтр отклика статического содержимого Quarkus
Есть ли способ добавить фильтр/перехватчик к статическим ресурсам, обслуживаемым из
META-INF/resources
?
Кажется, я перепробовал все возможные варианты:
@ServerResponseFilter
,
ContainerResponseFilter
,
WriterInterceptor
однако все эти функции вызываются только для
@Path
или же
@Route
...
Есть ли что-нибудь похожее на @RouteFilter, но для ответа?
2 ответа
Это единственные доступные:
public interface ClientRequestFilter {
void filter(ClientRequestContext requestContext) throws IOException;
}
public interface ClientResponseFilter {
void filter(ClientRequestContext requestContext,
ClientResponseContext responseContext) throws IOException;
}
public interface ContainerRequestFilter {
void filter(ContainerRequestContext requestContext) throws IOException;
}
public interface ContainerResponseFilter {
void filter(ContainerRequestContext requestContext,
ContainerResponseContext responseContext) throws IOException;
}
public interface ReaderInterceptor {
Object aroundReadFrom(ReaderInterceptorContext context)
throws java.io.IOException, javax.ws.rs.WebApplicationException;
}
public interface WriterInterceptor {
void aroundWriteTo(WriterInterceptorContext context)
throws java.io.IOException, javax.ws.rs.WebApplicationException;
}
Вы можете попробовать с
ClientResponseFilter
и увидеть:
В клиентском API ClientRequestFilter выполняется как часть конвейера вызовов до того, как HTTP-запрос будет доставлен в сеть.
ClientResponseFilter выполняется после получения ответа сервера, прежде чем управление будет возвращено приложению.
https://quarkus.io/specs/jaxrs/2.1/index.html#filters_and_interceptors
Кажется, что на данный момент нет ничего встроенного для изменения ответа статического контента, но ничто не мешает вам обслуживать контент динамически:
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.IOException;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
@Path("/")
@Produces(MediaType.TEXT_HTML)
public class FrontendController {
@GET
public Response index() throws IOException {
try (var index = getClass().getResourceAsStream(FrontendConstants.INDEX_RESOURCE)) {
if (index == null) {
throw new IOException("index.html file does not exist");
}
//modify index
return Response
.ok(index)
.cacheControl(FrontendConstants.NO_CACHE)
.build();
}
}
@GET
@Path("/{fileName:.+}")
public Response staticFile(@PathParam("fileName") String fileName) throws IOException {
try (var file = FrontendController.class.getResourceAsStream(FrontendConstants.FRONTEND_DIR + "/" + fileName)) {
if (file == null) {
return index();
}
var contentType = URLConnection.guessContentTypeFromStream(file);
return Response
.ok(
new String(file.readAllBytes(), StandardCharsets.UTF_8),
contentType == null ? MediaType.TEXT_PLAIN : contentType
)
.cacheControl(FrontendConstants.NO_CACHE)
.build();
}
}
}