Summary
Many people don't use Run()
to start their gin applications! This means TrustedProxies
is never parsed, as prepareTrustedCIDRs
is only ever called from this func.
There are a number of us whom host gin behind an nginx proxy_pass or apache reverse_proxy and would like to see something other than 127.0.0.1
in our request logs, among other facilities which require the ability to know the true Remote IP Address.
Details
Please see the quoted code from the repository:
gin.go L323:L367
// Run attaches the router to a http.Server and starts listening and serving HTTP requests.
// It is a shortcut for http.ListenAndServe(addr, router)
// Note: this method will block the calling goroutine indefinitely unless an error happens.
func (engine *Engine) Run(addr ...string) (err error) {
defer func() { debugPrintError(err) }()
trustedCIDRs, err := engine.prepareTrustedCIDRs()
if err != nil {
return err
}
engine.trustedCIDRs = trustedCIDRs
address := resolveAddress(addr)
debugPrint("Listening and serving HTTP on %s\n", address)
err = http.ListenAndServe(address, engine)
return
}
func (engine *Engine) prepareTrustedCIDRs() ([]*net.IPNet, error) {
if engine.TrustedProxies == nil {
return nil, nil
}
cidr := make([]*net.IPNet, 0, len(engine.TrustedProxies))
for _, trustedProxy := range engine.TrustedProxies {
if !strings.Contains(trustedProxy, "/") {
ip := parseIP(trustedProxy)
if ip == nil {
return cidr, &net.ParseError{Type: "IP address", Text: trustedProxy}
}
switch len(ip) {
case net.IPv4len:
trustedProxy += "/32"
case net.IPv6len:
trustedProxy += "/128"
}
}
_, cidrNet, err := net.ParseCIDR(trustedProxy)
if err != nil {
return cidr, err
}
cidr = append(cidr, cidrNet)
}
return cidr, nil
}}
Related Issue(s)
2697
2723
2791
2809
Comment From: AlbinoGeek
Even if #2791 is the accepted answer, I don't feel it should be closed until we have a commit sha or release to test this "fixed" functionality with the set function.
Comment From: duaneking
I'm using gin from an AWS Lambda. It works very well, via the adapter, but I bumped into this table edge pretty hard this morning and spent time looking into how to turn this off because it provides no value in my scenario, and actively gets in the way and slows things down.
I'm not a fan of this feature. To me its dead code, tbh.
Maybe Give us a ClientIPResolver interface instead, or something? Tie that in with any hosting provider specific modes, etc., seems best. At least then the code is open for extension but closed for modification, and hence is more SOLID and DRY.