clientId.go 852 B

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