更改 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 { Sql struct {
MysqlDsn string MysqlDsn string
} }
Node int64
Epoch int64
Debug bool Debug bool
JwtKey string JwtKey string
Cache struct { Cache struct {
Type string Type string
Ram int 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) { Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context() ctx := r.Context()
if sl.Enabled(ctx, slog.LevelInfo) { if sl.Enabled(ctx, slog.LevelInfo) {
ip, _ := utils.GetIP(r) ip, _ := utils.GetIP(r, c.RaelIP)
trackid.Add(1) trackid.Add(1)
ctx = setCtx(ctx, &reqInfo{ ctx = setCtx(ctx, &reqInfo{
URL: r.URL.String(), URL: r.URL.String(),

View File

@ -7,7 +7,8 @@ import (
"strings" "strings"
) )
func GetIP(r *http.Request) (string, error) { func GetIP(r *http.Request, fromHeader bool) (string, error) {
if fromHeader {
//Get IP from the X-REAL-IP header //Get IP from the X-REAL-IP header
ip := r.Header.Get("X-REAL-IP") ip := r.Header.Get("X-REAL-IP")
netIP := net.ParseIP(ip) netIP := net.ParseIP(ip)
@ -24,13 +25,14 @@ func GetIP(r *http.Request) (string, error) {
return ip, nil return ip, nil
} }
} }
}
//Get IP from RemoteAddr //Get IP from RemoteAddr
ip, _, err := net.SplitHostPort(r.RemoteAddr) ip, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil { if err != nil {
return "", err return "", err
} }
netIP = net.ParseIP(ip) netIP := net.ParseIP(ip)
if netIP != nil { if netIP != nil {
return ip, nil return ip, nil
} }