ProxyController.java 2.51 KB
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());
        });
    }
}
GitLab Appliance - Powered by TurnKey Linux