ProxyController.java
2.51 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
49
50
51
52
53
54
55
56
57
58
59
60
61
package com.sigem.gis.controller;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.util.StreamUtils;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Enumeration;
@RestController
public class ProxyController {
private final RestTemplate restTemplate;
private final String geoserverInternalBase = "http://proyecto-geoserver-1:8080";
public ProxyController(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
@RequestMapping(value = {"/geoserver/**", "/gwc/**"}, method = {RequestMethod.GET, RequestMethod.POST})
@ResponseBody
public ResponseEntity<byte[]> proxy(HttpServletRequest request) throws URISyntaxException {
String path = request.getRequestURI();
// Eliminamos el prefijo del contexto de la aplicación
if (path.startsWith("/gis-geoserver")) {
path = path.substring("/gis-geoserver".length());
}
// Si la petición viene por /gwc/, GeoServer la espera en /geoserver/gwc/
if (path.startsWith("/gwc")) {
path = "/geoserver" + path;
}
String query = request.getQueryString();
String fullUrl = geoserverInternalBase + path + (query != null ? "?" + query : "");
URI uri = new URI(fullUrl);
HttpHeaders headers = new HttpHeaders();
Enumeration<String> headerNames = request.getHeaderNames();
while (headerNames.hasMoreElements()) {
String hName = headerNames.nextElement();
// Evitamos pasar el Host original para que GeoServer no intente redirecciones externas
if (!hName.equalsIgnoreCase("host")) {
headers.add(hName, request.getHeader(hName));
}
}
return restTemplate.execute(uri, HttpMethod.valueOf(request.getMethod()), (req) -> {
req.getHeaders().putAll(headers);
if (request.getContentLength() > 0) StreamUtils.copy(request.getInputStream(), req.getBody());
}, (res) -> {
byte[] body = StreamUtils.copyToByteArray(res.getBody());
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.putAll(res.getHeaders());
// Sobrescribimos el content type si es necesario para asegurar la entrega de imágenes/PBF
return new ResponseEntity<>(body, responseHeaders, res.getStatusCode());
});
}
}