fix: 客户端实例上报 IP 地址优先使用 IPv4

新增 getClientIP 辅助函数,将 IPv6 环回地址(::1)转为 127.0.0.1,
避免在线客户端列表显示 IPv6 地址。
This commit is contained in:
2026-06-12 21:17:12 +08:00
parent 96c66c251b
commit 18b8c4c18b
+22 -2
View File
@@ -6,6 +6,7 @@ import (
"kenaito-conf/server/internal/logger" "kenaito-conf/server/internal/logger"
"kenaito-conf/server/internal/model" "kenaito-conf/server/internal/model"
"kenaito-conf/server/internal/service" "kenaito-conf/server/internal/service"
"net"
"net/http" "net/http"
"strconv" "strconv"
"time" "time"
@@ -13,6 +14,25 @@ import (
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
) )
// getClientIP 获取客户端 IPv4 地址,将 IPv6 环回地址转为 127.0.0.1
func getClientIP(c *gin.Context) string {
ip := c.ClientIP()
if ip == "" {
return ""
}
parsed := net.ParseIP(ip)
if parsed == nil {
return ip
}
if parsed.IsLoopback() {
return "127.0.0.1"
}
if v4 := parsed.To4(); v4 != nil {
return v4.String()
}
return ip
}
type ConfigApiHandler struct { type ConfigApiHandler struct {
parseService *service.ConfigParseService parseService *service.ConfigParseService
} }
@@ -107,7 +127,7 @@ func (h *ConfigApiHandler) FetchAllConfigs(c *gin.Context) {
result["latest.fetch.timestamp"] = strconv.FormatInt(time.Now().UnixMilli(), 10) result["latest.fetch.timestamp"] = strconv.FormatInt(time.Now().UnixMilli(), 10)
// record client instances asynchronously // record client instances asynchronously
go h.recordClientInstances(c.ClientIP(), configIds, req.AppName, req.Env, "fetchAll") go h.recordClientInstances(getClientIP(c), configIds, req.AppName, req.Env, "fetchAll")
c.JSON(http.StatusOK, result) c.JSON(http.StatusOK, result)
} }
@@ -197,7 +217,7 @@ func (h *ConfigApiHandler) FetchChangedConfigs(c *gin.Context) {
if len(configIds) > 0 { if len(configIds) > 0 {
fetchType = "fetchChanged" fetchType = "fetchChanged"
} }
go h.recordClientInstances(c.ClientIP(), allConfigIds, req.AppName, req.Env, fetchType) go h.recordClientInstances(getClientIP(c), allConfigIds, req.AppName, req.Env, fetchType)
c.JSON(http.StatusOK, model.WrapperResponse{Code: 0, Data: result}) c.JSON(http.StatusOK, model.WrapperResponse{Code: 0, Data: result})
} }