diff --git a/context.go b/context.go index e6cc4b3..6b8b7a9 100644 --- a/context.go +++ b/context.go @@ -4,7 +4,9 @@ import ( "bytes" "encoding/json" "io" + "net" "net/http" + "strings" "github.com/julienschmidt/httprouter" ) @@ -99,3 +101,17 @@ func (c *Context) Set(key string, value interface{}) { func (c *Context) Get(key string) interface{} { return c.store[key] } + +// RealIP uses proxy headers for the real ip, if none exist the IP of the current connection is returned +func (c *Context) RealIP() string { + if ip := c.Request.Header.Get(`X-Forwarded-For`); ip != `` { + return strings.Split(ip, `, `)[0] + } + + if ip := c.Request.Header.Get(`X-Real-IP`); ip != `` { + return ip + } + + ra, _, _ := net.SplitHostPort(c.Request.RemoteAddr) + return ra +}