Last active
February 11, 2019 15:33
-
-
Save trajano/63a630714be5c43a8390ae5a5e79f7f7 to your computer and use it in GitHub Desktop.
Add file/classpath support in Spring Cloud Gateway
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.springframework.cloud.gateway.filter.GatewayFilterChain; | |
import org.springframework.cloud.gateway.filter.GlobalFilter; | |
import org.springframework.cloud.gateway.route.Route; | |
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils; | |
import org.springframework.core.io.FileSystemResource; | |
import org.springframework.core.io.Resource; | |
import org.springframework.core.io.buffer.DataBufferUtils; | |
import org.springframework.http.server.reactive.ServerHttpResponse; | |
import org.springframework.stereotype.Component; | |
import org.springframework.web.server.ServerWebExchange; | |
import reactor.core.publisher.Mono; | |
/** | |
* Static resource using the {@code classpath:} or {@code file:} URI schemes. | |
*/ | |
@Component | |
public class FileSchemeGlobalFilter implements GlobalFilter { | |
@Override | |
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { | |
final Route route = exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR); | |
assert route != null; | |
if (!route.getUri().getScheme().equals("file")) { | |
return chain.filter(exchange); | |
} | |
final Resource resource = new FileSystemResource(route.getUri().getPath()); | |
ServerWebExchangeUtils.setAlreadyRouted(exchange); | |
return chain.filter(exchange).then(Mono.defer(() -> { | |
final ServerHttpResponse response = exchange.getResponse(); | |
return response.writeWith(DataBufferUtils.read(resource, response.bufferFactory(), 1024)); | |
})); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment