feat(engine): add trustedproxies and remoteIP (#2632)

Co-authored-by: Søren L. Hansen <soren@linux2go.dk>
Co-authored-by: Bo-Yi Wu <appleboy.tw@gmail.com>
Co-authored-by: thinkerou <thinkerou@gmail.com>
Co-authored-by: Javier Provecho Fernandez <javiertitan@gmail.com>
This commit is contained in:
Manu MA
2021-04-06 05:37:25 +02:00
committed by GitHub
parent f3de8132c5
commit bfc8ca285e
6 changed files with 392 additions and 23 deletions
+33
View File
@@ -2124,6 +2124,39 @@ func main() {
}
```
## Don't trust all proxies
Gin lets you specify which headers to hold the real client IP (if any),
as well as specifying which proxies (or direct clients) you trust to
specify one of these headers.
The `TrustedProxies` slice on your `gin.Engine` specifes network addresses or
network CIDRs from where clients which their request headers related to client
IP can be trusted. They can be IPv4 addresses, IPv4 CIDRs, IPv6 addresses or
IPv6 CIDRs.
```go
import (
"fmt"
"github.com/gin-gonic/gin"
)
func main() {
router := gin.Default()
router.TrustedProxies = []string{"192.168.1.2"}
router.GET("/", func(c *gin.Context) {
// If the client is 192.168.1.2, use the X-Forwarded-For
// header to deduce the original client IP from the trust-
// worthy parts of that header.
// Otherwise, simply return the direct client IP
fmt.Printf("ClientIP: %s\n", c.ClientIP())
})
router.Run()
}
```
## Testing