feat(ip-location): implement IP location querying and GeoIP database management
This commit is contained in:
@@ -0,0 +1,26 @@
|
||||
package tool
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/perfect-panel/server/internal/logic/admin/tool"
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/result"
|
||||
)
|
||||
|
||||
// QueryIPLocationHandler Query IP Location
|
||||
func QueryIPLocationHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
|
||||
return func(c *gin.Context) {
|
||||
var req types.QueryIPLocationRequest
|
||||
_ = c.ShouldBind(&req)
|
||||
validateErr := svcCtx.Validate(&req)
|
||||
if validateErr != nil {
|
||||
result.ParamErrorResult(c, validateErr)
|
||||
return
|
||||
}
|
||||
|
||||
l := tool.NewQueryIPLocationLogic(c.Request.Context(), svcCtx)
|
||||
resp, err := l.QueryIPLocation(&req)
|
||||
result.HttpResult(c, resp, err)
|
||||
}
|
||||
}
|
||||
@@ -10,7 +10,6 @@ import (
|
||||
// Get Client
|
||||
func GetClientHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
|
||||
return func(c *gin.Context) {
|
||||
|
||||
l := common.NewGetClientLogic(c.Request.Context(), svcCtx)
|
||||
resp, err := l.GetClient()
|
||||
result.HttpResult(c, resp, err)
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
package tool
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
|
||||
"github.com/perfect-panel/server/internal/svc"
|
||||
"github.com/perfect-panel/server/internal/types"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
"github.com/perfect-panel/server/pkg/xerr"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
type QueryIPLocationLogic struct {
|
||||
logger.Logger
|
||||
ctx context.Context
|
||||
svcCtx *svc.ServiceContext
|
||||
}
|
||||
|
||||
// NewQueryIPLocationLogic Query IP Location
|
||||
func NewQueryIPLocationLogic(ctx context.Context, svcCtx *svc.ServiceContext) *QueryIPLocationLogic {
|
||||
return &QueryIPLocationLogic{
|
||||
Logger: logger.WithContext(ctx),
|
||||
ctx: ctx,
|
||||
svcCtx: svcCtx,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *QueryIPLocationLogic) QueryIPLocation(req *types.QueryIPLocationRequest) (resp *types.QueryIPLocationResponse, err error) {
|
||||
if l.svcCtx.GeoIP == nil {
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.ERROR), " GeoIP database not configured")
|
||||
}
|
||||
|
||||
ip := net.ParseIP(req.IP)
|
||||
record, err := l.svcCtx.GeoIP.DB.City(ip)
|
||||
if err != nil {
|
||||
l.Errorf("Failed to query IP location: %v", err)
|
||||
return nil, errors.Wrapf(xerr.NewErrCode(xerr.ERROR), "Failed to query IP location")
|
||||
}
|
||||
|
||||
var country, region, city string
|
||||
if record.Country.Names != nil {
|
||||
country = record.Country.Names["en"]
|
||||
}
|
||||
if len(record.Subdivisions) > 0 && record.Subdivisions[0].Names != nil {
|
||||
region = record.Subdivisions[0].Names["en"]
|
||||
}
|
||||
if record.City.Names != nil {
|
||||
city = record.City.Names["en"]
|
||||
}
|
||||
|
||||
return &types.QueryIPLocationResponse{
|
||||
Country: country,
|
||||
Region: region,
|
||||
City: city,
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package svc
|
||||
|
||||
import (
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/oschwald/geoip2-golang"
|
||||
"github.com/perfect-panel/server/pkg/logger"
|
||||
)
|
||||
|
||||
const GeoIPDBURL = "https://raw.githubusercontent.com/adysec/IP_database/main/geolite/GeoLite2-City.mmdb"
|
||||
|
||||
type IPLocation struct {
|
||||
Path string
|
||||
DB *geoip2.Reader
|
||||
}
|
||||
|
||||
func NewIPLocation(path string) (*IPLocation, error) {
|
||||
|
||||
// 检查文件是否存在
|
||||
if _, err := os.Stat(path); os.IsNotExist(err) {
|
||||
logger.Infof("[GeoIP] Database not found, downloading from %s", GeoIPDBURL)
|
||||
// 文件不存在,下载数据库
|
||||
err := DownloadGeoIPDatabase(GeoIPDBURL, path)
|
||||
if err != nil {
|
||||
logger.Errorf("[GeoIP] Failed to download database: %v", err.Error())
|
||||
return nil, err
|
||||
}
|
||||
logger.Infof("[GeoIP] Database downloaded successfully")
|
||||
}
|
||||
|
||||
db, err := geoip2.Open(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &IPLocation{
|
||||
Path: path,
|
||||
DB: db,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (ipLoc *IPLocation) Close() error {
|
||||
return ipLoc.DB.Close()
|
||||
}
|
||||
|
||||
func DownloadGeoIPDatabase(url, path string) error {
|
||||
|
||||
// 创建路径, 确保目录存在
|
||||
err := os.MkdirAll(filepath.Dir(path), 0755)
|
||||
if err != nil {
|
||||
logger.Errorf("[GeoIP] Failed to create directory: %v", err.Error())
|
||||
return err
|
||||
}
|
||||
|
||||
// 创建文件
|
||||
out, err := os.Create(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer out.Close()
|
||||
|
||||
// 请求远程文件
|
||||
resp, err := http.Get(url)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
// 保存文件
|
||||
_, err = io.Copy(out, resp.Body)
|
||||
return err
|
||||
}
|
||||
@@ -37,6 +37,7 @@ type ServiceContext struct {
|
||||
Config config.Config
|
||||
Queue *asynq.Client
|
||||
ExchangeRate float64
|
||||
GeoIP *IPLocation
|
||||
|
||||
//NodeCache *cache.NodeCacheClient
|
||||
AuthModel auth.Model
|
||||
@@ -68,9 +69,17 @@ func NewServiceContext(c config.Config) *ServiceContext {
|
||||
db, err := orm.ConnectMysql(orm.Mysql{
|
||||
Config: c.MySQL,
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
panic(err.Error())
|
||||
}
|
||||
|
||||
// IP location initialize
|
||||
geoIP, err := NewIPLocation("./cache/GeoLite2-City.mmdb")
|
||||
if err != nil {
|
||||
panic(err.Error())
|
||||
}
|
||||
|
||||
rds := redis.NewClient(&redis.Options{
|
||||
Addr: c.Redis.Host,
|
||||
Password: c.Redis.Pass,
|
||||
@@ -89,6 +98,7 @@ func NewServiceContext(c config.Config) *ServiceContext {
|
||||
Config: c,
|
||||
Queue: NewAsynqClient(c),
|
||||
ExchangeRate: 1.0,
|
||||
GeoIP: geoIP,
|
||||
//NodeCache: cache.NewNodeCacheClient(rds),
|
||||
AuthLimiter: authLimiter,
|
||||
AdsModel: ads.NewModel(db, rds),
|
||||
|
||||
@@ -1571,6 +1571,16 @@ type QueryDocumentListResponse struct {
|
||||
List []Document `json:"list"`
|
||||
}
|
||||
|
||||
type QueryIPLocationRequest struct {
|
||||
IP string `form:"ip" validate:"required"`
|
||||
}
|
||||
|
||||
type QueryIPLocationResponse struct {
|
||||
Country string `json:"country"`
|
||||
Region string `json:"regio,omitempty"`
|
||||
City string `json:"city"`
|
||||
}
|
||||
|
||||
type QueryNodeTagResponse struct {
|
||||
Tags []string `json:"tags"`
|
||||
}
|
||||
@@ -2598,6 +2608,7 @@ type UserSubscribe struct {
|
||||
Token string `json:"token"`
|
||||
Status uint8 `json:"status"`
|
||||
Short string `json:"short"`
|
||||
Note string `json:"note"`
|
||||
CreatedAt int64 `json:"created_at"`
|
||||
UpdatedAt int64 `json:"updated_at"`
|
||||
}
|
||||
@@ -2617,6 +2628,7 @@ type UserSubscribeDetail struct {
|
||||
Upload int64 `json:"upload"`
|
||||
Token string `json:"token"`
|
||||
Status uint8 `json:"status"`
|
||||
Note string `json:"note"`
|
||||
CreatedAt int64 `json:"created_at"`
|
||||
UpdatedAt int64 `json:"updated_at"`
|
||||
}
|
||||
@@ -2635,6 +2647,7 @@ type UserSubscribeInfo struct {
|
||||
Upload int64 `json:"upload"`
|
||||
Token string `json:"token"`
|
||||
Status uint8 `json:"status"`
|
||||
Note string `json:"note"`
|
||||
CreatedAt int64 `json:"created_at"`
|
||||
UpdatedAt int64 `json:"updated_at"`
|
||||
IsTryOut bool `json:"is_try_out"`
|
||||
|
||||
Reference in New Issue
Block a user