package com.yd.csf.api.filter;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.util.ContentCachingRequestWrapper;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 缓存请求体的Filter，使切面中能读取原始HTTP请求体
 */
@Component
public class RequestCachingFilter extends OncePerRequestFilter {

    private static final Log log = LogFactory.getLog(RequestCachingFilter.class);

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {

        log.info("RequestCachingFilter doFilterInternal");

        try {
            // 如果不是 multipart/form-data，使用 ContentCachingRequestWrapper 包装
            String contentType = request.getContentType();
            boolean isMultipart = contentType != null && contentType.startsWith("multipart/form-data");
            if (!isMultipart) {
                ContentCachingRequestWrapper wrappedRequest = new ContentCachingRequestWrapper(request);
                filterChain.doFilter(wrappedRequest, response);
            } else {
                filterChain.doFilter(request, response);
            }
        } catch (Exception e) {
            logger.error("RequestCachingFilter异常", e);
            throw e;
        }
    }
}
