Created
July 14, 2015 15:18
-
-
Save danesparza/6b064e29d4eb89fff2cc to your computer and use it in GitHub Desktop.
Generates a random sequence of letters/numbers (for a sessionid or something)
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 ( | |
| "flag" | |
| "fmt" | |
| "math/rand" | |
| "time" | |
| ) | |
| var letters = []rune("abcdefghijklmnopqrstuvwxyz-+=.ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890") | |
| func main() { | |
| // Our flags | |
| length := flag.Int("length", 10, "Length of the sequence to generate") | |
| // Parse the command line for flags: | |
| flag.Parse() | |
| // Print out our sequence | |
| fmt.Println(randSeq(*length)) | |
| } | |
| func randSeq(n int) string { | |
| // Seed the random number generator with the current time | |
| rand.Seed(time.Now().UTC().UnixNano()) | |
| // Create a slice of runes of the correct length: | |
| b := make([]rune, n) | |
| // For each item in the slice, get a random character: | |
| for i := range b { | |
| b[i] = letters[rand.Intn(len(letters))] | |
| } | |
| // Return the string: | |
| return string(b) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment