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

     1  package ipgeo
     2  
     3  import (
     4  	"errors"
     5  	"github.com/oschwald/maxminddb-golang"
     6  	"net"
     7  	"os"
     8  	"strings"
     9  	"time"
    10  )
    11  
    12  const (
    13  	ipinfoDataBasePath = "./ipinfoLocal.mmdb"
    14  )
    15  
    16  func IPInfoLocal(ip string, _ time.Duration, _ string, _ bool) (*IPGeoData, error) {
    17  	if _, err := os.Stat(ipinfoDataBasePath); os.IsNotExist(err) {
    18  		panic("Cannot find ipinfoLocal.mmdb")
    19  	}
    20  	region, err := maxminddb.Open(ipinfoDataBasePath)
    21  	if err != nil {
    22  		panic("Cannot find ipinfoLocal.mmdb")
    23  	}
    24  	defer func(region *maxminddb.Reader) {
    25  		err := region.Close()
    26  		if err != nil {
    27  			panic(err)
    28  		}
    29  	}(region)
    30  	var record interface{}
    31  	searchErr := region.Lookup(net.ParseIP(ip), &record)
    32  	if searchErr != nil {
    33  		return &IPGeoData{}, errors.New("no results")
    34  	}
    35  	recordMap := record.(map[string]interface{})
    36  	countryName := recordMap["country_name"].(string)
    37  	prov := ""
    38  	if recordMap["country"].(string) == "HK" {
    39  		countryName = "China"
    40  		prov = "Hong Kong"
    41  	}
    42  	if recordMap["country"].(string) == "TW" {
    43  		countryName = "China"
    44  		prov = "Taiwan"
    45  	}
    46  	return &IPGeoData{
    47  		Asnumber: strings.TrimPrefix(recordMap["asn"].(string), "AS"),
    48  		Country:  countryName,
    49  		City:     "",
    50  		Prov:     prov,
    51  		Owner:    recordMap["as_name"].(string),
    52  	}, nil
    53  }