Fixed ip handling

This commit is contained in:
Asaf Gartner 2021-08-28 15:52:40 +03:00
parent 0179ee1993
commit e23f5fbcf6
1 changed files with 15 additions and 0 deletions

View File

@ -149,6 +149,9 @@ func (c *RequestContext) FullUrl() string {
return scheme + c.Req.Host + c.Req.URL.String() return scheme + c.Req.Host + c.Req.URL.String()
} }
// NOTE(asaf): Assumes port is present (it should be for RemoteAddr according to the docs)
var ipRegex = regexp.MustCompile(`^(\[(?P<addrv6>[^\]]+)\]:\d+)|((?P<addrv4>[^:]+):\d+)$`)
func (c *RequestContext) GetIP() *net.IPNet { func (c *RequestContext) GetIP() *net.IPNet {
ipString := "" ipString := ""
@ -168,6 +171,18 @@ func (c *RequestContext) GetIP() *net.IPNet {
if ipString == "" { if ipString == "" {
ipString = c.Req.RemoteAddr ipString = c.Req.RemoteAddr
if ipString != "" {
matches := ipRegex.FindStringSubmatch(ipString)
if matches != nil {
v4 := matches[ipRegex.SubexpIndex("addrv4")]
v6 := matches[ipRegex.SubexpIndex("addrv6")]
if v4 != "" {
ipString = v4
} else {
ipString = v6
}
}
}
} }
if ipString != "" { if ipString != "" {