Add Context.RealIP

This commit is contained in:
Nise Void 2020-04-06 16:41:26 +02:00
parent 2a612eb82f
commit d504c9d2b5
Signed by untrusted user: NiseVoid
GPG Key ID: FBA14AC83EA602F3

View File

@ -4,7 +4,9 @@ import (
"bytes" "bytes"
"encoding/json" "encoding/json"
"io" "io"
"net"
"net/http" "net/http"
"strings"
"github.com/julienschmidt/httprouter" "github.com/julienschmidt/httprouter"
) )
@ -99,3 +101,17 @@ func (c *Context) Set(key string, value interface{}) {
func (c *Context) Get(key string) interface{} { func (c *Context) Get(key string) interface{} {
return c.store[key] 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
}