package com.jeeplus.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Configuration
public class DomainFeignConfig {
    @Bean
    public RequestInterceptor requestInterceptor() {
        return new RequestInterceptor ( ) {
            @Override
            public void apply(RequestTemplate template) {
                // RequestContextHolder拿到调用方请求
                ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes ( );
                if ( attributes == null ) {
                    return;
                }
                // 老请求
                HttpServletRequest request = attributes.getRequest ( );
                // 同步请求头数据-domain
                String domain = request.getHeader ( "domain" );
                // 给被调用方微服务同步调用方请求domain
                template.header ( "domain", domain );
            }
        };
    }
}
