Search code examples
javamicronaut

Remove "Expires" HTTP header (for StreamedFiles)


In a micronaut filter I specify my own headers, e. g. I set the "Cache-Control" header with a "max-age" directive. Therefore I want to remove the "Expires" header because by using "Cache-Control" the "Expires" header is ignored 1.

When returning a StreamedFile from a filter the "Expires" and "Date" header is set by FileTypeHandler 2 and I do not know how to change this.

Are there options to change this?

Example:

@Filter("/**")
public class MyFilter implements HttpServerFilter {

    @Inject
    ImageService imageService;

    @Override
    public Publisher<MutableHttpResponse<?>> doFilter(HttpRequest<?> request, ServerFilterChain chain) {
        File image = imageService.getImage(request);

        return Publishers.just(
                HttpResponse.ok(new StreamedFile(new FileInputStream(image), MediaType.IMAGE_JPEG_TYPE))
                        .header("Cache-Control", "max-age=31449600")
                        .header("Access-Control-Allow-Methods", "GET")
                        .header("Referrer-Policy",  "same-origin")
        );
    }

}

Solution

  • Not sure why exactly you want to return a file from a filter

    If it is just the method you identified that bother you generating this headers, you can just override it :

    @Singleton
    @Replaces(FileTypeHandler.class)
    public class CustomFileTypeHandler extends FileTypeHandler {
    
        public CustomFileTypeHandler(FileTypeHandlerConfiguration configuration) {
            super(configuration);
        }
    
        @Override
        protected void setDateAndCacheHeaders(MutableHttpResponse response, long lastModified) {
            //do nothing
        }
    }