Skip to content

Instantly share code, notes, and snippets.

@elithrar
Created June 5, 2014 11:50
Show Gist options
  • Save elithrar/b65046f21a8c78d7f5bb to your computer and use it in GitHub Desktop.
Save elithrar/b65046f21a8c78d7f5bb to your computer and use it in GitHub Desktop.
GenerateShortGUID() - generate a 8-byte, URL-safe ID for slightly saner URLs with a very low collision chance (http://goo.gl/VWAFOo) and avoid http://example.com/thing/550e8400-e29b-41d4-a716-446655440000 ugliness. Leverages Go's existing cryptographically secure random number generator: http://elithrar.github.io/article/generating-secure-random…
// GenerateRandomBytes generates a crytographically secure random byte string using crypto/rand.
func GenerateRandomBytes(s int) ([]byte, error) {
b := make([]byte, s)
n, err := rand.Read(b)
if n != len(b) || err != nil {
return nil, fmt.Errorf("Unable to successfully read from the system CSPRNG (%v)", err)
}
return b, nil
}
// GenerateRandomString generates a crytographically secure, URL-safe base64-encoded string.
func GenerateRandomString(s int) (string, error) {
b, err := GenerateRandomBytes(s)
if err != nil {
return "", err
}
return base64.URLEncoding.EncodeToString(b), nil
}
// GenerateShortGUID generates an 8-byte short pseudo-GUID and returns a URL-safe base64-encoded string.
// Note: Collision chance (birthday paradox) is approx. .000000002% after 100,000 GUIDs.
// See http://goo.gl/VWAFOo for more details.
func GenerateShortGUID() (string, error) {
id, err := GenerateRandomString(8)
if err != nil {
return "", err
}
return id, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment