- 实现配置文件加载和解析功能,支持服务器、MMDB数据库和日志配置 - 集成GeoLite2城市数据库查询,提供IP地理位置信息查询服务 - 添加私有IP地址检测逻辑,过滤本地网络地址段 - 构建HTTP路由处理器,返回JSON格式的IP位置信息 - 配置默认启动参数和错误处理机制 - 集成日志系统,记录请求处理过程和错误信息
53 lines
1.1 KiB
Go
53 lines
1.1 KiB
Go
package app
|
|
|
|
import (
|
|
"net/http"
|
|
|
|
"checkIP/internal/mmdb"
|
|
"checkIP/internal/network"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/sirupsen/logrus"
|
|
)
|
|
|
|
func NewRouter(reader *mmdb.Reader) *gin.Engine {
|
|
router := gin.New()
|
|
router.Use(gin.Recovery())
|
|
router.Use(gin.LoggerWithWriter(logrus.StandardLogger().Out))
|
|
|
|
router.GET("/", func(c *gin.Context) {
|
|
ip := c.ClientIP()
|
|
if ip == "" {
|
|
c.String(http.StatusBadRequest, "Invalid IP")
|
|
return
|
|
}
|
|
|
|
ipInfo := network.GetIPInformation(ip)
|
|
fields := logrus.Fields{
|
|
"ip": ipInfo.IP,
|
|
"is_private": ipInfo.IsPrivate,
|
|
}
|
|
if ipInfo.IsPrivate {
|
|
fields["private_cidr"] = ipInfo.PrivateCIDR
|
|
}
|
|
logrus.WithFields(fields).Info("ip check")
|
|
|
|
if ipInfo.IsPrivate {
|
|
c.String(http.StatusBadRequest, "Invalid IP")
|
|
return
|
|
}
|
|
|
|
ipLocation, err := reader.QueryIP(ipInfo.IP)
|
|
if err != nil {
|
|
logrus.WithError(err).Error("mmdb lookup failed")
|
|
c.Status(http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
logrus.WithField("ip_info", ipLocation).Info("mmdb lookup")
|
|
c.JSON(http.StatusOK, ipLocation)
|
|
})
|
|
|
|
return router
|
|
}
|