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 main

import (
"crypto/rand"
"encoding/base64"
"encoding/hex"
"log"
)

func main() {
h, b, err := random(10)
if err != nil {
log.Fatalln(err)
}

log.Println("Hexadecimal:", h)
log.Println("Base64: ", b)
}

func random(length int) (string, string, error) {
bytes := make([]byte, length)

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

return hex.EncodeToString(bytes), base64.StdEncoding.EncodeToString(bytes), nil
}

Tests


# 10
cdd13b760e
zdE7dg4=

# 100
0c39b2d81dcaadf0eb5113a786cdf6548d65b8b25c5896ef0957ef4b6f9d538b2b96bdc6c2bb5796c351ad02daefa3e88eff
DDmy2B3KrfDrUROnhs32VI1luLJcWJbvCVfvS2+dU4srlr3GwrtXlsNRrQLa76Pojv8=

Non-secure version - 1


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 - 2


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