randomid.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. package common
  2. import (
  3. "crypto/rand"
  4. "encoding/hex"
  5. "io"
  6. "strconv"
  7. )
  8. // TruncateID returns a shorthand version of a string identifier for convenience.
  9. // A collision with other shorthands is very unlikely, but possible.
  10. // In case of a collision a lookup with TruncIndex.Get() will fail, and the caller
  11. // will need to use a langer prefix, or the full-length Id.
  12. func TruncateID(id string) string {
  13. shortLen := 12
  14. if len(id) < shortLen {
  15. shortLen = len(id)
  16. }
  17. return id[:shortLen]
  18. }
  19. // GenerateRandomID returns an unique id
  20. func GenerateRandomID() string {
  21. for {
  22. id := make([]byte, 32)
  23. if _, err := io.ReadFull(rand.Reader, id); err != nil {
  24. panic(err) // This shouldn't happen
  25. }
  26. value := hex.EncodeToString(id)
  27. // if we try to parse the truncated for as an int and we don't have
  28. // an error then the value is all numberic and causes issues when
  29. // used as a hostname. ref #3869
  30. if _, err := strconv.ParseInt(TruncateID(value), 10, 64); err == nil {
  31. continue
  32. }
  33. return value
  34. }
  35. }
  36. func RandomString() string {
  37. id := make([]byte, 32)
  38. if _, err := io.ReadFull(rand.Reader, id); err != nil {
  39. panic(err) // This shouldn't happen
  40. }
  41. return hex.EncodeToString(id)
  42. }