- 实现配置文件加载和解析功能,支持服务器、MMDB数据库和日志配置 - 集成GeoLite2城市数据库查询,提供IP地理位置信息查询服务 - 添加私有IP地址检测逻辑,过滤本地网络地址段 - 构建HTTP路由处理器,返回JSON格式的IP位置信息 - 配置默认启动参数和错误处理机制 - 集成日志系统,记录请求处理过程和错误信息
50 lines
1.1 KiB
Go
50 lines
1.1 KiB
Go
package mmdb
|
|
|
|
import (
|
|
"fmt"
|
|
"net"
|
|
|
|
"github.com/IncSW/geoip2"
|
|
)
|
|
|
|
type IpInfo struct {
|
|
Ip string `json:"ip"`
|
|
CountryIsoCode string `json:"country_iso_code"`
|
|
CountryName string `json:"country_name"`
|
|
City string `json:"city"`
|
|
TimeZone string `json:"time_zone"`
|
|
}
|
|
|
|
type Reader struct {
|
|
reader *geoip2.CityReader
|
|
}
|
|
|
|
func New(filePath string) (*Reader, error) {
|
|
if filePath == "" {
|
|
return nil, fmt.Errorf("mmdb file path is empty")
|
|
}
|
|
r, err := geoip2.NewCityReaderFromFile(filePath)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("open mmdb: %w", err)
|
|
}
|
|
return &Reader{reader: r}, nil
|
|
}
|
|
|
|
func (r *Reader) QueryIP(ip string) (IpInfo, error) {
|
|
if r == nil || r.reader == nil {
|
|
return IpInfo{}, fmt.Errorf("mmdb reader not initialized")
|
|
}
|
|
record, err := r.reader.Lookup(net.ParseIP(ip))
|
|
if err != nil {
|
|
return IpInfo{}, fmt.Errorf("lookup ip: %w", err)
|
|
}
|
|
info := IpInfo{
|
|
Ip: ip,
|
|
CountryIsoCode: record.Country.ISOCode,
|
|
CountryName: record.Country.Names["en"],
|
|
City: record.City.Names["en"],
|
|
TimeZone: record.Location.TimeZone,
|
|
}
|
|
return info, nil
|
|
}
|