Skip to content

Instantly share code, notes, and snippets.

@devlights
Created August 14, 2024 15:22
Show Gist options
  • Save devlights/7534500bfe62c566bf944553ae8974e8 to your computer and use it in GitHub Desktop.
Save devlights/7534500bfe62c566bf944553ae8974e8 to your computer and use it in GitHub Desktop.
Generate random strings in Golang
package main
import (
"bytes"
"io"
"math/rand"
"os"
"time"
)
const (
charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
)
func randomString(buf []byte) {
var (
unixNano = time.Now().UnixNano()
rndSource = rand.NewSource(unixNano)
rnd = rand.New(rndSource)
)
for i := range buf {
buf[i] = charset[rnd.Intn(len(charset))]
}
}
func main() {
buf := make([]byte, 1<<5)
randomString(buf)
_, _ = io.Copy(os.Stdout, bytes.NewReader(buf))
}
/*
$ go run main.go
HIk2fRYqwschgPhWfGo1SsnkZMdamTQN
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment