feat: c.IP add use-proxy-header arg
This commit is contained in:
parent
9b7c8d9d24
commit
bf1c5ad92f
19
ctx.go
19
ctx.go
@ -14,6 +14,10 @@ import (
|
|||||||
"sync"
|
"sync"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
forwardHeaders = []string{"CF-Connecting-IP", "X-Forwarded-For", "X-Real-Ip"}
|
||||||
|
)
|
||||||
|
|
||||||
type Ctx struct {
|
type Ctx struct {
|
||||||
lock sync.Mutex
|
lock sync.Mutex
|
||||||
writermem responseWriter
|
writermem responseWriter
|
||||||
@ -191,11 +195,24 @@ func (c *Ctx) Get(key string, defaultValue ...string) string {
|
|||||||
return value
|
return value
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Ctx) IP() string {
|
func (c *Ctx) IP(useProxyHeader ...bool) string {
|
||||||
ip, _, err := net.SplitHostPort(strings.TrimSpace(c.Request.RemoteAddr))
|
ip, _, err := net.SplitHostPort(strings.TrimSpace(c.Request.RemoteAddr))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if len(useProxyHeader) > 0 && useProxyHeader[0] {
|
||||||
|
for _, h := range forwardHeaders {
|
||||||
|
for _, rip := range strings.Split(c.Request.Header.Get(h), ",") {
|
||||||
|
realIP := net.ParseIP(strings.Replace(rip, " ", "", -1))
|
||||||
|
if check := net.ParseIP(realIP.String()); check != nil {
|
||||||
|
ip = realIP.String()
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return ip
|
return ip
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Loading…
x
Reference in New Issue
Block a user