You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

realip.go 1.6KB

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