package org.ta.pddserver.utils;

import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;

@Slf4j
public class HttpRequestHandlerTool {

    public static String getClientIP(HttpServletRequest request) {

        String xForwardedFor = request.getHeader("X-Forwarded-For");
        if (xForwardedFor != null && !xForwardedFor.isEmpty()) {

            return xForwardedFor.split(",")[0].trim();
        }

        String xRealIP = request.getHeader("X-Real-IP");
        if (xRealIP != null && !xRealIP.isEmpty()) {

            return xRealIP;
        }

        return request.getRemoteAddr();
    }

    /**
     * 获取请求消息体文本
     *
     * @param request 请求
     * @return 消息体文本
     */
    public static String getStringFromRequest(HttpServletRequest request) {
        StringBuffer buffer = new StringBuffer();
        String line = null;
        try {
            BufferedReader reader = request.getReader();
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }
        } catch (IOException e) {
            log.error(e.getMessage());
        }
        return buffer.toString();
    }
}
