Skip to content

Commit

Permalink
customizable client ip extractor
Browse files Browse the repository at this point in the history
  • Loading branch information
billyplus committed Jan 11, 2021
1 parent 4d2dad5 commit 023eb48
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 0 deletions.
4 changes: 4 additions & 0 deletions context.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
// Use X-Forwarded-For before X-Real-Ip as nginx uses X-Real-Ip with the proxy's IP.
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 {
clientIP := c.requestHeader("X-Forwarded-For")
clientIP = strings.TrimSpace(strings.Split(clientIP, ",")[0])
Expand Down
8 changes: 8 additions & 0 deletions context_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1416,6 +1416,14 @@ func TestContextClientIP(t *testing.T) {
// no port
c.Request.RemoteAddr = "50.50.50.50"
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) {
Expand Down
3 changes: 3 additions & 0 deletions gin.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,9 @@ type Engine struct {
HandleMethodNotAllowed 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
// 'X-AppEngine...' for better integration with that PaaS.
AppEngine bool
Expand Down

0 comments on commit 023eb48

Please sign in to comment.