Skip to content

Commit

Permalink
Try to get user's IP
Browse files Browse the repository at this point in the history
  • Loading branch information
Piszmog committed Jun 8, 2024
1 parent 5428c2c commit 926aa18
Showing 1 changed file with 16 additions and 4 deletions.
20 changes: 16 additions & 4 deletions server/handler/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,10 @@ package handler
import (
"context"
"log/slog"
"net"
"net/http"
"strconv"
"strings"

"github.com/Piszmog/pathwise/db"
"github.com/a-h/templ"
Expand Down Expand Up @@ -47,9 +49,19 @@ func getUserID(r *http.Request) (int64, error) {
}

func getClientIP(r *http.Request) string {
ip := r.Header.Get("X-FORWARD-FOR")
if ip != "" {
return ip
xff := r.Header.Get("X-Forwarded-For")
if xff != "" {
ip := strings.Split(xff, ",")[0]
ip = strings.TrimSpace(ip)
if net.ParseIP(ip) != nil {
return ip
}
}
return r.RemoteAddr

ip, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
return r.RemoteAddr
}

return ip
}

0 comments on commit 926aa18

Please sign in to comment.