package parser

import (
	"errors"
	"github.com/go-resty/resty/v2"
	"strings"
)

type IpInfo struct {
	Addr    string
	Country string
}

func getIpv4Info() (*IpInfo, error) {
	rsp, err := resty.New().R().Get("https://www.cloudflare.com/cdn-cgi/trace")
	if err != nil {
		return nil, err
	}
	var info IpInfo
	pars := strings.Split(rsp.String(), "\n")
	for _, v := range pars {
		par := strings.Split(v, "=")
		if len(par) != 2 {
			return nil, errors.New("parse rsp failed")
		}
		switch par[0] {
		case "ip":
			info.Addr = par[1]
		case "loc":
			info.Country = strings.ToLower(par[1])
		}
	}
	if info.Addr == "" {
		return nil, errors.New("parse addr failed")
	}
	if info.Country == "" {
		return nil, errors.New("parse country failed")
	}
	return &info, nil
}
