Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- import (
- "crypto/rand"
- "encoding/hex"
- "fmt"
- "github.com/docker/docker/pkg/random"
- "io"
- "strconv"
- "strings"
- )
- const shortLen = 12
- func main() {
- for i := 0; i < 10; i++ {
- fmt.Println(generateID(true))
- }
- }
- func generateID(crypto bool) string {
- b := make([]byte, 32)
- r := random.Reader
- if crypto {
- r = rand.Reader
- }
- for {
- if _, err := io.ReadFull(r, b); err != nil {
- panic(err) // This shouldn't happen
- }
- id := hex.EncodeToString(b)
- // if we try to parse the truncated for as an int and we don't have
- // an error then the value is all numeric and causes issues when
- // used as a hostname. ref #3869
- if _, err := strconv.ParseInt(TruncateID(id), 10, 64); err == nil {
- continue
- }
- return id
- }
- }
- func TruncateID(id string) string {
- if i := strings.IndexRune(id, ':'); i >= 0 {
- id = id[i+1:]
- }
- trimTo := shortLen
- if len(id) < shortLen {
- trimTo = len(id)
- }
- return id[:trimTo]
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement