realip.go 1.8 KB

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