Last active
June 18, 2020 10:47
-
-
Save pataiji/f3239b4ef79927c2e10319c47ee25e9f to your computer and use it in GitHub Desktop.
Generate a short unique string from UUID in Go
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 ( | |
"encoding/base32" | |
"fmt" | |
"github.com/google/uuid" | |
) | |
func main() { | |
u := uuid.New() | |
fmt.Printf("generated uuid: %s\n", u) | |
su, _ := shortenUUID(u) | |
fmt.Printf("shorten uuid: %s\n", su) | |
du, _ := unshortenUUID(su) | |
fmt.Printf("decoded uuid: %s\n", du) | |
} | |
func shortenUUID(u uuid.UUID) (string, error) { | |
b, err := u.MarshalBinary() | |
if err != nil { | |
return "", err | |
} | |
encoding := getBase32Encoding() | |
s := encoding.EncodeToString(b) | |
return s, nil | |
} | |
func unshortenUUID(s string) (*uuid.UUID, error) { | |
encoding := getBase32Encoding() | |
b, err := encoding.DecodeString(s) | |
if err != nil { | |
return nil, err | |
} | |
u, err := uuid.FromBytes(b) | |
return &u, err | |
} | |
func getBase32Encoding() *base32.Encoding { | |
return base32.StdEncoding.WithPadding(base32.NoPadding) | |
} |
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
$ go run shortUUID.go | |
generated uuid: 1b96f573-1856-499a-89a5-179157748710 | |
shorten uuid: DOLPK4YYKZEZVCNFC6IVO5EHCA | |
decoded uuid: 1b96f573-1856-499a-89a5-179157748710 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment