package cn.reghao.tnb.gateway.limiter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.cloud.gateway.route.Route;
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Optional;

/**
 * @author reghao
 * @date 2023-09-14 11:51:58
 */
@Slf4j
//@Component
public class MyKeyResolver implements KeyResolver {
    @Override
    public Mono<String> resolve(ServerWebExchange exchange) {
        HttpHeaders httpHeaders = exchange.getRequest().getHeaders();
        String loginId = httpHeaders.get("x-login-id").get(0);
        String userId = httpHeaders.get("x-user-id").get(0);
        String remoteAddress = exchange.getRequest().getRemoteAddress().getHostString();
        String requestUrl = exchange.getRequest().getPath().value();
        return Mono.just(String.format("%s:%s", userId, requestUrl));

        /*Route route = exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR);
        ServerHttpRequest request = exchange.getRequest();
        String uri = request.getURI().getPath();
        log.info("限流的 URI: {}", uri);
        return Mono.just(Optional.ofNullable(route).map(Route::getId).orElse("") + "/" + uri);*/
    }
}
