Skip to content

Instantly share code, notes, and snippets.

@xigang
Created April 24, 2017 07:31
Show Gist options
  • Save xigang/9b340b256d658ffff5722fc74af5574a to your computer and use it in GitHub Desktop.
Save xigang/9b340b256d658ffff5722fc74af5574a to your computer and use it in GitHub Desktop.
copy from docker
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]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment