package generate import ( "crypto/rand" "encoding/binary" mathRand "math/rand" "strconv" ) const alphabet = "0123456789abcdefghijklmnopqrstuvwxyz" func generateWeak(length int, prefix string) string { result := prefix for len(result) < length { result += string(alphabet[mathRand.Intn(len(alphabet))]) } return result } // Generate generates an ID either strongly or weakly depending on the system. func Generate(length int, prefix string) string { var buffer [32]byte result := prefix offset := 0 _, err := rand.Read(buffer[:32]) if err != nil { return generateWeak(length, prefix) } for len(result) < length { result += strconv.FormatUint(binary.LittleEndian.Uint64(buffer[offset:]), 36) offset += 8 if offset >= 32 { _, err = rand.Read(buffer[:32]) if err != nil { return generateWeak(length, prefix) } offset = 0 } } return result[:length] }