arimelody-web/controller/ip.go

28 lines
833 B
Go
Raw Normal View History

2025-02-07 16:40:58 +00:00
package controller
import (
"arimelody-web/model"
"net/http"
"slices"
"strings"
2025-02-07 16:40:58 +00:00
)
// Returns the request's original IP address, resolving the `x-forwarded-for`
// header if the request originates from a trusted proxy.
2025-02-07 16:54:36 +00:00
func ResolveIP(app *model.AppState, r *http.Request) string {
2026-05-01 17:14:13 +01:00
iSplit := strings.LastIndex(r.RemoteAddr, ":")
addr := r.RemoteAddr[0:iSplit]
2025-02-07 16:54:36 +00:00
if slices.Contains(app.Config.TrustedProxies, addr) {
2025-02-07 16:40:58 +00:00
forwardedFor := r.Header.Get("x-forwarded-for")
if len(forwardedFor) > 0 {
// discard extra IPs; cloudflare tends to append their nodes
forwardedFor = strings.Split(forwardedFor, ", ")[0]
2026-05-01 17:14:13 +01:00
addr = forwardedFor
2025-02-07 16:40:58 +00:00
}
}
2026-05-01 17:14:13 +01:00
if addr[0] == '[' && addr[len(addr) - 1] == ']' {
addr = addr[1:len(addr) - 1]
}
2025-02-07 16:54:36 +00:00
return addr
2025-02-07 16:40:58 +00:00
}