package com.fdkankan.gateway.util;

import cn.hutool.core.util.StrUtil;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;

public class WebUtil {

    private final static String UNKNOWN = "unknown";

    /**
     * 获取客户端请求终端地址
     * @param request  客户端请求request
     * @return  终端ip地址
     */
    public static String getIpAddress(ServerHttpRequest request) {
        HttpHeaders headers = request.getHeaders();
        String ip = headers.getFirst("X-Forwarded-For");
        if(StrUtil.isNotBlank(ip) && UNKNOWN.equalsIgnoreCase(ip)){
            if(ip.indexOf(",") != -1){
                ip = ip.split(",")[0];
                return ip;
            }
        }
        ip = headers.getFirst("Proxy-Client-IP");
        if(StrUtil.isNotBlank(ip)) return ip;
        ip = headers.getFirst("WL-Proxy-Client-IP");
        if(StrUtil.isNotBlank(ip)) return ip;
        ip = headers.getFirst("HTTP-CLIENT-IP");
        if(StrUtil.isNotBlank(ip)) return ip;
        ip = headers.getFirst("HTTP-X-FORWARDED-FOR");
        if(StrUtil.isNotBlank(ip)) return ip;
        ip = headers.getFirst("X-Real-IP");
        if(StrUtil.isNotBlank(ip)) return ip;
        ip = request.getRemoteAddress().getAddress().getHostAddress();
        return ip;
    }
}
