If you wish to create a cryptography secure or non-secure random string with variable length, you can use examples below.


Cryptography secure version


package random

import (
"math/rand"
"time"
)

const chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"

func String(length int) (string, error) {
rand.Seed(time.Now().UnixNano())

bytes := make([]byte, length)

_, err := rand.Read(bytes)
if err != nil {
return "", err
}

for k, v := range bytes {
bytes[k] = chars[v%byte(len(chars))]
}

return string(bytes), nil
}

Tests


# 10
uhPv8zBz1K

# 100
k547x6Dhm1xfuAtQpEdfg30fZ147nEcb59suGtdanLu0mXVhEooayMo8A7FVa3HtNxoE984vbVc0UD8LpPsBSXj0C7KqPa7TxZbN

Non-secure version


package random

import (
"math/rand"
"time"
)

var chars = []rune("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")

func String(length int) string {
rand.Seed(time.Now().UnixNano())

pick := make([]rune, length)
for i := range pick {
pick[i] = chars[rand.Intn(len(chars))]
}

return string(pick)
}

Tests


# 10
57fCgGTwQf

# 100
Mu1gbzW3N5kQNHDL5yZN4WJNH0zyWUWw8UYiVGgAaNjSGyyRyG1cTz1MISIMT31IyG0tn5ADIpOucko5BfjkdUdvqgKDmDKT7Xsg