refactor🎨: 调整客户端ip获取方法以及日志中对应位置更新

This commit is contained in:
zhangwenjian committed 2021-06-13 21:20:07 +08:00
1 parent ed52efaa44
commit e0cf7af7a9
4 files changed
+28 -10

No files matched your search

+17
View File
@@ -0,0 +1,17 @@
package common
import (
"github.com/gin-gonic/gin"
"strings"
)
func GetClientIP(ctx *gin.Context) string {
ip := ctx.Request.Header.Get("X-Forwarded-For")
if strings.Contains(ip, "127.0.0.1") || ip == "" {
ip = ctx.Request.Header.Get("X-real-ip")
}
if ip == "" {
return "127.0.0.1"
}
return ip
}
+2 -1
View File
@@ -2,6 +2,7 @@ package middleware
import (
"fmt"
"go-admin/common"
"net/http"
"strconv"
"strings"
@@ -33,7 +34,7 @@ func CustomError(c *gin.Context) {
c.Request.URL,
statusCode,
c.Request.RequestURI,
c.ClientIP(),
common.GetClientIP(c),
p[2],
)
c.JSON(http.StatusOK, gin.H{
+5 -2
View File
@@ -1,7 +1,9 @@
package handler
import (
"fmt"
"go-admin/app/admin/models"
"go-admin/common"
"net/http"
"github.com/gin-gonic/gin"
@@ -115,8 +117,9 @@ func LoginLogToDB(c *gin.Context, status string, msg string, username string) {
l := make(map[string]interface{})
ua := user_agent.New(c.Request.UserAgent())
l["ipaddr"] = c.ClientIP()
l["loginLocation"] = pkg.GetLocation(c.ClientIP(),gaConfig.ExtConfig.AMap.Key)
l["ipaddr"] = common.GetClientIP(c)
fmt.Println("gaConfig.ExtConfig.AMap.Key", gaConfig.ExtConfig.AMap.Key)
l["loginLocation"] = pkg.GetLocation(common.GetClientIP(c),gaConfig.ExtConfig.AMap.Key)
l["loginTime"] = pkg.GetCurrentTime()
l["status"] = status
l["remark"] = c.Request.UserAgent()
+4 -7
View File
@@ -5,6 +5,7 @@ import (
"bytes"
"encoding/json"
"fmt"
"go-admin/common"
gaConfig "go-admin/config"
"io"
"io/ioutil"
@@ -80,12 +81,7 @@ func LoggerToFile() gin.HandlerFunc {
// 状态码
statusCode := c.Writer.Status()
// 请求IP
clientIP := c.ClientIP()
fmt.Println("Headers:", c.Request.Header.Get("X-Real-IP"))
fmt.Println("clientIP:", clientIP)
clientIP := common.GetClientIP(c)
// 执行时间
latencyTime := endTime.Sub(startTime)
// 日志格式
@@ -111,6 +107,7 @@ func SetDBOperLog(c *gin.Context, clientIP string, statusCode int, reqUri string
l["_fullPath"] = c.FullPath()
l["operUrl"] = reqUri
l["operIp"] = clientIP
fmt.Println("gaConfig.ExtConfig.AMap.Key", gaConfig.ExtConfig.AMap.Key)
l["operLocation"] = pkg.GetLocation(clientIP, gaConfig.ExtConfig.AMap.Key)
l["operName"] = user.GetUserName(c)
l["requestMethod"] = c.Request.Method
@@ -135,4 +132,4 @@ func SetDBOperLog(c *gin.Context, clientIP string, statusCode int, reqUri string
log.Errorf("Append message error, %s", err.Error())
}
}
}
}