From d504c9d2b516cca9e8a51398fce1661ffe291094 Mon Sep 17 00:00:00 2001 From: NiseVoid Date: Mon, 6 Apr 2020 16:41:26 +0200 Subject: [PATCH] Add Context.RealIP --- context.go | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) 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 +}