github.com/hellobchain/third_party@v0.0.0-20230331131523-deb0478a2e52/go-chi/chi/middleware/realip.go (about)

     1  package middleware
     2  
     3  // Ported from Goji's middleware, source:
     4  // https://github.com/zenazn/goji/tree/master/web/middleware
     5  
     6  import (
     7  	"strings"
     8  
     9  	"github.com/hellobchain/newcryptosm/http"
    10  )
    11  
    12  var xForwardedFor = http.CanonicalHeaderKey("X-Forwarded-For")
    13  var xRealIP = http.CanonicalHeaderKey("X-Real-IP")
    14  
    15  // RealIP is a middleware that sets a http.Request's RemoteAddr to the results
    16  // of parsing either the X-Forwarded-For header or the X-Real-IP header (in that
    17  // order).
    18  //
    19  // This middleware should be inserted fairly early in the middleware stack to
    20  // ensure that subsequent layers (e.g., request loggers) which examine the
    21  // RemoteAddr will see the intended value.
    22  //
    23  // You should only use this middleware if you can trust the headers passed to
    24  // you (in particular, the two headers this middleware uses), for example
    25  // because you have placed a reverse proxy like HAProxy or nginx in front of
    26  // Goji. If your reverse proxies are configured to pass along arbitrary header
    27  // values from the client, or if you use this middleware without a reverse
    28  // proxy, malicious clients will be able to make you very sad (or, depending on
    29  // how you're using RemoteAddr, vulnerable to an attack of some sort).
    30  func RealIP(h http.Handler) http.Handler {
    31  	fn := func(w http.ResponseWriter, r *http.Request) {
    32  		if rip := realIP(r); rip != "" {
    33  			r.RemoteAddr = rip
    34  		}
    35  		h.ServeHTTP(w, r)
    36  	}
    37  
    38  	return http.HandlerFunc(fn)
    39  }
    40  
    41  func realIP(r *http.Request) string {
    42  	var ip string
    43  
    44  	if xff := r.Header.Get(xForwardedFor); xff != "" {
    45  		i := strings.Index(xff, ", ")
    46  		if i == -1 {
    47  			i = len(xff)
    48  		}
    49  		ip = xff[:i]
    50  	} else if xrip := r.Header.Get(xRealIP); xrip != "" {
    51  		ip = xrip
    52  	}
    53  
    54  	return ip
    55  }