IP库增加多个辅助查询函数

This commit is contained in:
GoEdgeLab
2023-08-24 12:21:26 +08:00
parent 018c1e5dee
commit adfbc04078
3 changed files with 74 additions and 0 deletions

View File

@@ -53,6 +53,18 @@ func LookupIP(ip string) *QueryResult {
return defaultLibrary.LookupIP(ip)
}
// LookupIPSummaries 查询一组IP对应的区域描述
func LookupIPSummaries(ipList []string) map[string]string /** ip => summary **/ {
var result = map[string]string{}
for _, ip := range ipList {
var region = LookupIP(ip)
if region != nil && region.IsOk() {
result[ip] = region.Summary()
}
}
return result
}
type IPLibrary struct {
reader *Reader
}

View File

@@ -86,6 +86,41 @@ func TestIPLibrary_LookupIP(t *testing.T) {
}
}
func TestIPLibrary_LookupIP_Summary(t *testing.T) {
var lib = iplibrary.NewIPLibrary()
err := lib.InitFromData(iplibrary.DefaultIPLibraryData(), "")
if err != nil {
t.Fatal(err)
}
for _, ip := range []string{
"66.249.66.69",
"123456", // wrong ip
"", // empty
} {
var result = lib.LookupIP(ip)
if result.IsOk() {
t.Log(ip, "=>", "region summary:", result.RegionSummary(), "summary:", result.Summary())
} else {
t.Log(ip, "=>", "region summary:", result.RegionSummary(), "summary:", result.Summary())
}
}
}
func TestIPLibrary_LookupIPSummaries(t *testing.T) {
_ = iplibrary.InitDefault()
t.Logf("%+v", iplibrary.LookupIPSummaries([]string{
"127.0.0.1",
"8.8.8.8",
"4.4.4.4",
"202.96.0.20",
"111.197.165.199",
"66.249.66.69",
"2222", // wrong ip
"2406:8c00:0:3401:133:18:168:70", // ipv6
}))
}
func BenchmarkIPLibrary_Lookup(b *testing.B) {
var lib = iplibrary.NewIPLibrary()
err := lib.InitFromData(iplibrary.DefaultIPLibraryData(), "")

View File

@@ -183,6 +183,33 @@ func (this *QueryResult) Summary() string {
return strings.Join(pieces, " ")
}
func (this *QueryResult) RegionSummary() string {
if this.item == nil {
return ""
}
var pieces = []string{}
var countryName = this.CountryName()
var provinceName = this.ProvinceName()
var cityName = this.CityName()
var townName = this.TownName()
if len(countryName) > 0 {
pieces = append(pieces, countryName)
}
if len(provinceName) > 0 && !lists.ContainsString(pieces, provinceName) {
pieces = append(pieces, provinceName)
}
if len(cityName) > 0 && !lists.ContainsString(pieces, cityName) && !lists.ContainsString(pieces, strings.TrimSuffix(cityName, "市")) {
pieces = append(pieces, cityName)
}
if len(townName) > 0 && !lists.ContainsString(pieces, townName) && !lists.ContainsString(pieces, strings.TrimSuffix(townName, "县")) {
pieces = append(pieces, townName)
}
return strings.Join(pieces, " ")
}
func (this *QueryResult) realCountryId() uint16 {
if this.item != nil {
switch item := this.item.(type) {