Config.java
2.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package com.huaheng.gateway.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.WebFilter;
import reactor.core.publisher.Mono;
import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR;
import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.addOriginalRequestUrl;
@Configuration
public class Config {
@Value("${server.prefix}")
private String prefix;
@Bean
@Order(-1)
public WebFilter apiPrefixFilter() {
return (exchange, chain) -> {
ServerHttpRequest request = exchange.getRequest();
addOriginalRequestUrl(exchange, request.getURI());
String path = request.getURI().getRawPath();
if (!path.contains(prefix) && !path.contains("/actuator/health") && !path.contains("/jmreport")) {
ServerHttpResponse response = exchange.getResponse();
response.setStatusCode(HttpStatus.BAD_GATEWAY);
DataBuffer buffer = response
.bufferFactory()
.wrap(HttpStatus.BAD_GATEWAY.getReasonPhrase().getBytes());
return response.writeWith(Mono.just(buffer));
}
String newPath = "";
if (path.contains("/jmreport") && !path.contains("report/jmreport")) {
newPath = "/report"+path;
} else {
newPath = path.replaceFirst(prefix, "");
}
ServerHttpRequest newRequest = request.mutate().path(newPath).build();
exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR, newRequest.getURI());
return chain.filter(exchange.mutate().request(newRequest).build());
};
}
}