clientId.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. package utils
  2. import (
  3. "crypto/md5" //nolint
  4. "encoding/hex"
  5. "net"
  6. "net/http"
  7. "strings"
  8. log "github.com/sirupsen/logrus"
  9. )
  10. // GenerateClientIDFromRequest generates a client id from the provided request.
  11. func GenerateClientIDFromRequest(req *http.Request) string {
  12. ipAddress := GetIPAddressFromRequest(req)
  13. clientID := ipAddress + req.UserAgent()
  14. // Create a MD5 hash of this ip + useragent
  15. b := md5.Sum([]byte(clientID)) // nolint
  16. return hex.EncodeToString(b[:])
  17. }
  18. // GetIPAddressFromRequest returns the IP address from a http request.
  19. func GetIPAddressFromRequest(req *http.Request) string {
  20. ipAddressString := req.RemoteAddr
  21. xForwardedFor := req.Header.Get("X-FORWARDED-FOR")
  22. if xForwardedFor != "" {
  23. ipAddressString = strings.Split(xForwardedFor, ", ")[0]
  24. }
  25. if !strings.Contains(ipAddressString, ":") {
  26. return ipAddressString
  27. }
  28. if isIPv6(ipAddressString) && !strings.Contains(ipAddressString, "[") {
  29. return ipAddressString
  30. }
  31. ip, _, err := net.SplitHostPort(ipAddressString)
  32. if err != nil {
  33. log.Errorln(err)
  34. return ""
  35. }
  36. return ip
  37. }
  38. func isIPv6(address string) bool {
  39. return strings.Count(address, ":") >= 2
  40. }