更改 ip 获取位置

This commit is contained in:
xmdhs 2023-09-05 01:38:25 +08:00
parent 0932141498
commit 38c274b106
No known key found for this signature in database
GPG Key ID: E809D6D43DEFCC95
3 changed files with 17 additions and 16 deletions

View File

@ -10,12 +10,11 @@ type Config struct {
Sql struct {
MysqlDsn string
}
Node int64
Epoch int64
Debug bool
JwtKey string
Cache struct {
Type string
Ram int
}
RaelIP bool
}

View File

@ -21,7 +21,7 @@ func NewServer(c config.Config, sl *slog.Logger, route *httprouter.Router) (*htt
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
if sl.Enabled(ctx, slog.LevelInfo) {
ip, _ := utils.GetIP(r)
ip, _ := utils.GetIP(r, c.RaelIP)
trackid.Add(1)
ctx = setCtx(ctx, &reqInfo{
URL: r.URL.String(),

View File

@ -7,22 +7,24 @@ import (
"strings"
)
func GetIP(r *http.Request) (string, error) {
//Get IP from the X-REAL-IP header
ip := r.Header.Get("X-REAL-IP")
netIP := net.ParseIP(ip)
if netIP != nil {
return ip, nil
}
//Get IP from X-FORWARDED-FOR header
ips := r.Header.Get("X-FORWARDED-FOR")
splitIps := strings.Split(ips, ",")
for _, ip := range splitIps {
func GetIP(r *http.Request, fromHeader bool) (string, error) {
if fromHeader {
//Get IP from the X-REAL-IP header
ip := r.Header.Get("X-REAL-IP")
netIP := net.ParseIP(ip)
if netIP != nil {
return ip, nil
}
//Get IP from X-FORWARDED-FOR header
ips := r.Header.Get("X-FORWARDED-FOR")
splitIps := strings.Split(ips, ",")
for _, ip := range splitIps {
netIP := net.ParseIP(ip)
if netIP != nil {
return ip, nil
}
}
}
//Get IP from RemoteAddr
@ -30,7 +32,7 @@ func GetIP(r *http.Request) (string, error) {
if err != nil {
return "", err
}
netIP = net.ParseIP(ip)
netIP := net.ParseIP(ip)
if netIP != nil {
return ip, nil
}