github.com/nxtrace/NTrace-core@v1.3.1-0.20240513132635-39169291e8c9/ipgeo/chunzhen.go (about)

     1  package ipgeo
     2  
     3  import (
     4  	"encoding/json"
     5  	"github.com/nxtrace/NTrace-core/util"
     6  	"io"
     7  	"log"
     8  	"net/http"
     9  	"strings"
    10  	"time"
    11  )
    12  
    13  func Chunzhen(ip string, timeout time.Duration, _ string, _ bool) (*IPGeoData, error) {
    14  	url := util.GetenvDefault("NEXTTRACE_CHUNZHENURL", "http://127.0.0.1:2060") + "?ip=" + ip
    15  	client := &http.Client{
    16  		// 2 秒超时
    17  		Timeout: timeout,
    18  	}
    19  	req, _ := http.NewRequest("GET", url, nil)
    20  	content, err := client.Do(req)
    21  	if err != nil {
    22  		log.Println("纯真 请求超时(2s),请切换其他API使用")
    23  		return &IPGeoData{}, err
    24  	}
    25  	body, _ := io.ReadAll(content.Body)
    26  
    27  	var data map[string]interface{}
    28  	err = json.Unmarshal(body, &data)
    29  	if err != nil {
    30  		return &IPGeoData{}, err
    31  	}
    32  	city := data[ip].(map[string]interface{})["area"].(string)
    33  	region := data[ip].(map[string]interface{})["country"].(string)
    34  	var asn string
    35  	if data[ip].(map[string]interface{})["asn"] != nil {
    36  		asn = data[ip].(map[string]interface{})["asn"].(string)
    37  	}
    38  	// 判断是否前两个字为香港或台湾
    39  	var country string
    40  	provinces := []string{
    41  		"北京",
    42  		"天津",
    43  		"河北",
    44  		"山西",
    45  		"内蒙古",
    46  		"辽宁",
    47  		"吉林",
    48  		"黑龙江",
    49  		"上海",
    50  		"江苏",
    51  		"浙江",
    52  		"安徽",
    53  		"福建",
    54  		"江西",
    55  		"山东",
    56  		"河南",
    57  		"湖北",
    58  		"湖南",
    59  		"广东",
    60  		"广西",
    61  		"海南",
    62  		"重庆",
    63  		"四川",
    64  		"贵州",
    65  		"云南",
    66  		"西藏",
    67  		"陕西",
    68  		"甘肃",
    69  		"青海",
    70  		"宁夏",
    71  		"新疆",
    72  		"台湾",
    73  		"香港",
    74  		"澳门",
    75  	}
    76  	for _, province := range provinces {
    77  		if strings.Contains(region, province) {
    78  			country = "中国"
    79  			city = region + city
    80  			break
    81  		}
    82  	}
    83  	if country == "" {
    84  		country = region
    85  	}
    86  	return &IPGeoData{
    87  		Asnumber: asn,
    88  		Country:  country,
    89  		City:     city,
    90  	}, nil
    91  }