package helper

import (
	"context"
	"github.com/go-kratos/kratos/v2/transport/http"
	"net"
	"strings"
)

// GetHeaderRealIP 获取header头中的真实IP
func GetHeaderRealIP(ctx context.Context) string {
	serverContext, isOk := http.RequestFromServerContext(ctx)
	if isOk {
		return serverContext.Header.Get("X-Real-Ip")
	}
	return ""
}

// GetClientIP 获取客户端IP
func GetClientIP(r *http.Request) string {
	xForwardedFor := r.Header.Get("X-Forwarded-For")
	ip := strings.TrimSpace(strings.Split(xForwardedFor, ",")[0])
	if ip != "" {
		return ip
	}

	ip = strings.TrimSpace(r.Header.Get("X-Real-Ip"))
	if ip != "" {
		return ip
	}

	if ip, _, err := net.SplitHostPort(strings.TrimSpace(r.RemoteAddr)); err == nil {
		return ip
	}

	return ""
}

// IPString2Long 把ip字符串转为数值(ipv4)
func IPString2Long(ip string) uint {
	b := net.ParseIP(ip).To4()
	if b == nil {
		return 0
	}
	return uint(b[3]) | uint(b[2])<<8 | uint(b[1])<<16 | uint(b[0])<<24
}
