Created
August 21, 2015 04:57
-
-
Save erikhoward/f36413c277c92396fc59 to your computer and use it in GitHub Desktop.
Go random token generator
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 ( | |
| "crypto/rand" | |
| "encoding/base64" | |
| "fmt" | |
| ) | |
| func GenerateRandomBytes(n int) ([]byte, error) { | |
| b := make([]byte, n) | |
| _, err := rand.Read(b) | |
| // if err == nill only if we read len(b) bytes | |
| if err != nil { | |
| return nil, err | |
| } | |
| return b, nil | |
| } | |
| func GenerateRandomString(s int) (string, error) { | |
| b, err := GenerateRandomBytes(s) | |
| return base64.URLEncoding.EncodeToString(b), err | |
| } | |
| func main() { | |
| token, err := GenerateRandomString(32) | |
| if err != nil { | |
| fmt.Println("Error generating token") | |
| } | |
| fmt.Printf("Token: %s", token) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment