szaydel
1/23/2019 - 8:08 PM

Generate a random string of a given length in Golang

package main

import (
	"fmt"
	"math/rand"
	"time"
)

func randString(length int) string {
	const charset = "abcdefghijklmnopqrstuvwxyz" +
		"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
	rs := rand.New(
		rand.NewSource(time.Now().UnixNano()))
	b := make([]byte, length)
	for i := range b {
		b[i] = charset[rs.Intn(len(charset))]
	}
	return string(b)
}

func main() {
	fmt.Printf("%s\n", randString(32))
}