Created
August 14, 2024 15:22
-
-
Save devlights/7534500bfe62c566bf944553ae8974e8 to your computer and use it in GitHub Desktop.
Generate random strings in Golang
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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