Skip to content

Instantly share code, notes, and snippets.

@0xffan
Last active June 24, 2022 13:49
Show Gist options
  • Save 0xffan/af82331c331abcf27a56a024530ec399 to your computer and use it in GitHub Desktop.
Save 0xffan/af82331c331abcf27a56a024530ec399 to your computer and use it in GitHub Desktop.
Reverse proxy using spring-cloud-gateway-mvc
package com.example.reverseproxy;
import com.example.ApiResponse;
import org.springframework.cloud.gateway.mvc.ProxyExchange;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;
@RestController
@RequestMapping(ReverseProxyController.PROXY_MAPPING_PREFIX)
public class ReverseProxyController {
public static final String PROXY_MAPPING_PREFIX = "/proxy/";
@RequestMapping("/**")
public ResponseEntity<?> postProxy(ProxyExchange<ApiResponse> proxyExchange, HttpServletRequest request) {
String path = proxyExchange.path(PROXY_MAPPING_PREFIX);
String queryString = request.getQueryString();
if (null != queryString) path = path + "?" + queryString;
proxyExchange.uri("http://localhost:8092/" + path);
return switch (Objects.requireNonNull(HttpMethod.resolve(request.getMethod()))) {
case POST -> proxyExchange.post(responseEntity -> {
if (responseEntity.getStatusCode() == HttpStatus.OK) {
System.out.printf("POST Response: %s\n", responseEntity.getBody());
}
return responseEntity;
});
case GET -> proxyExchange.get(responseEntity -> {
if (responseEntity.getStatusCode() == HttpStatus.OK) {
System.out.printf("GET Response: %s\n", responseEntity.getBody());
}
return responseEntity;
});
default -> ResponseEntity.status(HttpStatus.METHOD_NOT_ALLOWED).build();
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment