github.com/mailgun/holster/v4@v4.20.0/random/random.go (about)

     1  package random
     2  
     3  import (
     4  	"crypto/rand"
     5  	"fmt"
     6  	"strings"
     7  )
     8  
     9  const NumericRunes = "0123456789"
    10  const LowerAlphaRunes = "abcdefghijklmnopqrstuvwxyz"
    11  const UpperAlphaRunes = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    12  const AlphaRunes = UpperAlphaRunes + LowerAlphaRunes
    13  
    14  // Return a random string made up of characters passed
    15  func Runes(prefix string, length int, runes ...string) string {
    16  	chars := strings.Join(runes, "")
    17  	var bytes = make([]byte, length)
    18  	_, err := rand.Read(bytes)
    19  	if err != nil {
    20  		// TODO(v5): Return this error instead?
    21  		panic(fmt.Errorf("while reading random bytes: %w", err))
    22  	}
    23  
    24  	for i, b := range bytes {
    25  		bytes[i] = chars[b%byte(len(chars))]
    26  	}
    27  	return prefix + string(bytes)
    28  }
    29  
    30  // Return a random string of alpha characters
    31  func Alpha(prefix string, length int) string {
    32  	return Runes(prefix, length, AlphaRunes)
    33  }
    34  
    35  // Return a random string of alpha and numeric characters
    36  func String(prefix string, length int) string {
    37  	return Runes(prefix, length, AlphaRunes, NumericRunes)
    38  }
    39  
    40  // Given a list of strings, return one of the strings randomly
    41  func Item(items ...string) string {
    42  	var bytes = make([]byte, 1)
    43  	_, err := rand.Read(bytes)
    44  	if err != nil {
    45  		// TODO(v5): Return this error instead?
    46  		panic(fmt.Errorf("while reading random bytes: %w", err))
    47  	}
    48  
    49  	return items[bytes[0]%byte(len(items))]
    50  }
    51  
    52  // Return a random domain name in the form "randomAlpha.net"
    53  func DomainName() string {
    54  	return fmt.Sprintf("%s.%s",
    55  		Alpha("", 14),
    56  		Item("net", "com", "org", "io", "gov"))
    57  }