package cn.component.util;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import cn.constant.HttpConst;
import cn.util.core.LogKit;
import cn.util.core.ServletKit;

import java.net.InetAddress;
import java.net.UnknownHostException;

import javax.servlet.http.HttpServletRequest;

/**
 * 服务相关配置
 */
@Component
@Configuration
public class HttpService
{
    /**
     * 获取完整的请求路径，包括：域名，端口，上下文访问路径
     * @return 服务地址 比如：http://www.localhost:8080
     */
    public String getUrl(){
        HttpServletRequest request = ServletKit.getRequest();
        return getDomain(request);
    }

    public static String getDomain(HttpServletRequest request)
    {
        StringBuffer url = request.getRequestURL();
        String contextPath = request.getServletContext().getContextPath();
        return url.delete(url.length() - request.getRequestURI().length(), url.length())
        		.append(contextPath)
        		.toString();
    }
    
    @Value("${server.port}")
    private String serverPort;
    /**
     * 项目获取当前服务的IP端口地址
     * 返回格式：http://192.168.1.2:8080
     */
    public String getUrlPort() 
    {
        InetAddress address = null;
        try {
            address = InetAddress.getLocalHost();
        } catch (UnknownHostException e) {
           LogKit.info(e);
        }
        return HttpConst.HTTP_SLASH + address.getHostAddress() + ":" + serverPort;
    }
}

