client_ip.go 979 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. // Copyright 2018 Frédéric Guillot. All rights reserved.
  2. // Use of this source code is governed by the Apache 2.0
  3. // license that can be found in the LICENSE file.
  4. package request // import "miniflux.app/http/request"
  5. import (
  6. "net"
  7. "net/http"
  8. "strings"
  9. )
  10. // FindClientIP returns client real IP address.
  11. func FindClientIP(r *http.Request) string {
  12. headers := []string{"X-Forwarded-For", "X-Real-Ip"}
  13. for _, header := range headers {
  14. value := r.Header.Get(header)
  15. if value != "" {
  16. addresses := strings.Split(value, ",")
  17. address := strings.TrimSpace(addresses[0])
  18. if net.ParseIP(address) != nil {
  19. return address
  20. }
  21. }
  22. }
  23. // Fallback to TCP/IP source IP address.
  24. var remoteIP string
  25. if strings.ContainsRune(r.RemoteAddr, ':') {
  26. remoteIP, _, _ = net.SplitHostPort(r.RemoteAddr)
  27. } else {
  28. remoteIP = r.RemoteAddr
  29. }
  30. // When listening on a Unix socket, RemoteAddr is empty.
  31. if remoteIP == "" {
  32. remoteIP = "127.0.0.1"
  33. }
  34. return remoteIP
  35. }