Advertisement
Guest User

Untitled

a guest
Apr 24th, 2017
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.92 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4. "crypto/rand"
  5. "encoding/hex"
  6. "fmt"
  7. "github.com/docker/docker/pkg/random"
  8. "io"
  9. "strconv"
  10. "strings"
  11. )
  12.  
  13. const shortLen = 12
  14.  
  15. func main() {
  16. for i := 0; i < 10; i++ {
  17. fmt.Println(generateID(true))
  18. }
  19. }
  20.  
  21. func generateID(crypto bool) string {
  22. b := make([]byte, 32)
  23. r := random.Reader
  24. if crypto {
  25. r = rand.Reader
  26. }
  27. for {
  28. if _, err := io.ReadFull(r, b); err != nil {
  29. panic(err) // This shouldn't happen
  30. }
  31. id := hex.EncodeToString(b)
  32. // if we try to parse the truncated for as an int and we don't have
  33. // an error then the value is all numeric and causes issues when
  34. // used as a hostname. ref #3869
  35. if _, err := strconv.ParseInt(TruncateID(id), 10, 64); err == nil {
  36. continue
  37. }
  38. return id
  39. }
  40. }
  41.  
  42. func TruncateID(id string) string {
  43. if i := strings.IndexRune(id, ':'); i >= 0 {
  44. id = id[i+1:]
  45. }
  46. trimTo := shortLen
  47. if len(id) < shortLen {
  48. trimTo = len(id)
  49. }
  50. return id[:trimTo]
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement