refactor(重构代码): 重构并保持接口兼容

This commit is contained in:
2026-01-08 11:14:24 +08:00
parent cc141ac4f5
commit 999c6f1442
11 changed files with 511 additions and 261 deletions

View File

@@ -1,32 +1,101 @@
package qqwry
import (
"fmt"
"testing"
)
func init() {
if err := LoadFile("assets/qqwry.ipdb"); err != nil {
panic(err)
// TestClient_QueryIP 测试实例IP查询功能
func TestClient_QueryIP(t *testing.T) {
tests := []struct {
name string
filePath string
ipAddrList []string
}{
{
name: "DAT数据库",
filePath: "assets/qqwry.dat",
ipAddrList: []string{
"119.29.29.29",
"8.8.8.8",
},
},
{
name: "IPDB数据库",
filePath: "assets/qqwry.ipdb",
ipAddrList: []string{
"119.29.29.29",
"8.8.8.8",
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
client, err := NewClient(tt.filePath)
if err != nil {
t.Fatal(err)
}
for _, ip := range tt.ipAddrList {
location, err := client.QueryIP(ip)
if err != nil {
t.Error(err)
continue
}
fmt.Printf("国家:%s省份%s城市%s区县%s运营商%s\n",
location.Country,
location.Province,
location.City,
location.District,
location.ISP,
)
}
})
}
}
func TestQueryIP(t *testing.T) {
queryIp := "119.29.29.29"
location, err := QueryIP(queryIp)
if err != nil {
t.Fatal(err)
// TestGlobal_QueryIP 测试全局IP查询功能
func TestGlobal_QueryIP(t *testing.T) {
tests := []struct {
name string
filePath string
ipAddrList []string
}{
{
name: "兼容性-DAT",
filePath: "assets/qqwry.dat",
ipAddrList: []string{
"119.29.29.29",
"8.8.8.8",
},
},
{
name: "兼容性-IPDB",
filePath: "assets/qqwry.ipdb",
ipAddrList: []string{
"119.29.29.29",
"8.8.8.8",
},
},
}
emptyVal := func(val string) string {
if val != "" {
return val
}
return "未知"
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if err := LoadFile(tt.filePath); err != nil {
t.Fatal(err)
}
for _, ip := range tt.ipAddrList {
location, err := QueryIP(ip)
if err != nil {
t.Error(err)
continue
}
fmt.Printf("国家:%s省份%s城市%s区县%s运营商%s\n",
location.Country,
location.Province,
location.City,
location.District,
location.ISP,
)
}
})
}
t.Logf("国家:%s省份%s城市%s区县%s运营商%s",
emptyVal(location.Country),
emptyVal(location.Province),
emptyVal(location.City),
emptyVal(location.District),
emptyVal(location.ISP),
)
}