Skip to content

Instantly share code, notes, and snippets.

@erikhoward
Created August 21, 2015 04:57
Show Gist options
  • Save erikhoward/f36413c277c92396fc59 to your computer and use it in GitHub Desktop.
Save erikhoward/f36413c277c92396fc59 to your computer and use it in GitHub Desktop.
Go random token generator
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