mirror of
https://github.com/gin-gonic/gin.git
synced 2025-10-18 06:42:10 +08:00
customizable client ip extractor
This commit is contained in:
parent
4d2dad5961
commit
023eb48b10
@ -729,6 +729,10 @@ func (c *Context) ShouldBindBodyWith(obj interface{}, bb binding.BindingBody) (e
|
|||||||
// X-Real-IP and X-Forwarded-For in order to work properly with reverse-proxies such us: nginx or haproxy.
|
// X-Real-IP and X-Forwarded-For in order to work properly with reverse-proxies such us: nginx or haproxy.
|
||||||
// Use X-Forwarded-For before X-Real-Ip as nginx uses X-Real-Ip with the proxy's IP.
|
// Use X-Forwarded-For before X-Real-Ip as nginx uses X-Real-Ip with the proxy's IP.
|
||||||
func (c *Context) ClientIP() string {
|
func (c *Context) ClientIP() string {
|
||||||
|
if c.engine.ClientIPExtractor != nil {
|
||||||
|
// if you don't trust your proxies, you can define your own extractor for client IP
|
||||||
|
return c.engine.ClientIPExtractor(c.Request)
|
||||||
|
}
|
||||||
if c.engine.ForwardedByClientIP {
|
if c.engine.ForwardedByClientIP {
|
||||||
clientIP := c.requestHeader("X-Forwarded-For")
|
clientIP := c.requestHeader("X-Forwarded-For")
|
||||||
clientIP = strings.TrimSpace(strings.Split(clientIP, ",")[0])
|
clientIP = strings.TrimSpace(strings.Split(clientIP, ",")[0])
|
||||||
|
@ -1416,6 +1416,14 @@ func TestContextClientIP(t *testing.T) {
|
|||||||
// no port
|
// no port
|
||||||
c.Request.RemoteAddr = "50.50.50.50"
|
c.Request.RemoteAddr = "50.50.50.50"
|
||||||
assert.Empty(t, c.ClientIP())
|
assert.Empty(t, c.ClientIP())
|
||||||
|
|
||||||
|
// custome client IP extractor
|
||||||
|
c.engine.ClientIPExtractor = func(req *http.Request) string {
|
||||||
|
clientIP := c.requestHeader("My-Client-IP")
|
||||||
|
return clientIP
|
||||||
|
}
|
||||||
|
c.Request.Header.Set("My-Client-IP", "10.10.10.10")
|
||||||
|
assert.Equal(t, "10.10.10.10", c.ClientIP())
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestContextContentType(t *testing.T) {
|
func TestContextContentType(t *testing.T) {
|
||||||
|
3
gin.go
3
gin.go
@ -83,6 +83,9 @@ type Engine struct {
|
|||||||
HandleMethodNotAllowed bool
|
HandleMethodNotAllowed bool
|
||||||
ForwardedByClientIP bool
|
ForwardedByClientIP bool
|
||||||
|
|
||||||
|
// Custom extractor for extracting client IP from request
|
||||||
|
ClientIPExtractor func(*http.Request) string
|
||||||
|
|
||||||
// #726 #755 If enabled, it will thrust some headers starting with
|
// #726 #755 If enabled, it will thrust some headers starting with
|
||||||
// 'X-AppEngine...' for better integration with that PaaS.
|
// 'X-AppEngine...' for better integration with that PaaS.
|
||||||
AppEngine bool
|
AppEngine bool
|
||||||
|
Loading…
x
Reference in New Issue
Block a user