feat: 支持ip转地址

This commit is contained in:
ydajiang
2025-10-31 17:17:52 +08:00
parent 4f4fc016f4
commit f351a10819
9 changed files with 134 additions and 26 deletions

View File

@@ -45,6 +45,9 @@ type Config_ struct {
Position string `json:"position"`
OnInvite string `json:"on_invite"`
}
IP2RegionDBPath string
IP2RegionEnable bool
}
type LogConfig struct {
@@ -84,6 +87,8 @@ func ParseConfig(path string) (*Config_, error) {
SubPTZGlobalInterval: load.Section("sip").Key("sub_ptz_global_interval").MustInt(),
DeviceDefaultMediaTransport: load.Section("sip").Key("device_default_media_transport").String(),
GlobalDropChannelType: load.Section("sip").Key("global_drop_channel_type").String(),
IP2RegionDBPath: load.Section("ip2region").Key("db_path").String(),
IP2RegionEnable: load.Section("ip2region").Key("enable").MustBool(),
}
config_.Hooks.Online = load.Section("hooks").Key("online").String()

65
common/ip2region.go Normal file
View File

@@ -0,0 +1,65 @@
package common
import (
"github.com/lionsoul2014/ip2region/binding/golang/xdb"
"strings"
)
var (
searcher *xdb.Searcher
)
func LoadIP2RegionDB(path string) error {
// 1、从 dbPath 加载整个 xdb 到内存
cBuff, err := xdb.LoadContentFromFile(path)
if err != nil {
return err
}
// 2、用全局的 cBuff 创建完全基于内存的查询对象。
searcher, err = xdb.NewWithBuffer(xdb.IPv4, cBuff)
if err != nil {
return err
}
return nil
}
func IP2Region(ip string) (string, error) {
// 3、查询
region, err := searcher.SearchByStr(ip)
if err != nil {
return "", err
}
// 合并成一个地址
var addressList []string
for _, address := range strings.Split(region, "|") {
if address == "" || address == "中国" || address == "0" {
continue
}
var same bool
for _, s := range addressList {
if s == address {
same = true
break
}
}
if same {
continue
}
addressList = append(addressList, address)
}
if length := len(addressList); length == 0 {
return "", nil
} else if length > 1 {
// 最后一个地址空格分开
addressList[length-2] += " "
}
return strings.Join(addressList, ""), nil
}