xff.go 577 B

123456789101112131415161718192021222324252627
  1. package middleware
  2. import (
  3. "net"
  4. "net/http"
  5. )
  6. const xForwardedFor = "X-Forwarded-For"
  7. func getIP(req *http.Request) string {
  8. ip, _, err := net.SplitHostPort(req.RemoteAddr)
  9. if err != nil {
  10. return req.RemoteAddr
  11. }
  12. return ip
  13. }
  14. // XFF is a middleware to identifying the originating IP address using X-Forwarded-For header
  15. func XFF(inner http.Handler) http.Handler {
  16. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  17. xff := r.Header.Get(xForwardedFor)
  18. if xff == "" {
  19. r.Header.Set(xForwardedFor, getIP(r))
  20. }
  21. inner.ServeHTTP(w, r)
  22. })
  23. }