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

     1  package ipgeo
     2  
     3  import (
     4  	"io"
     5  	"net/http"
     6  	"time"
     7  
     8  	"github.com/tidwall/gjson"
     9  )
    10  
    11  func IPInSight(ip string, timeout time.Duration, _ string, _ bool) (*IPGeoData, error) {
    12  	client := &http.Client{
    13  		// 2 秒超时
    14  		Timeout: timeout,
    15  	}
    16  	resp, err := client.Get("https://api.ipinsight.io/ip/" + ip + "?token=" + token.ipinsight)
    17  	if err != nil {
    18  		return nil, err
    19  	}
    20  	body, err := io.ReadAll(resp.Body)
    21  	if err != nil {
    22  		return nil, err
    23  	}
    24  
    25  	res := gjson.ParseBytes(body)
    26  
    27  	return &IPGeoData{
    28  		Country: res.Get("country_name").String(),
    29  		City:    res.Get("city_name").String(),
    30  		Prov:    res.Get("region_name").String(),
    31  	}, nil
    32  }