Skip to content

Instantly share code, notes, and snippets.

@hasbro17
Created October 24, 2018 21:50
Show Gist options
  • Save hasbro17/201d727ca6402c067dd399a8a059c32c to your computer and use it in GitHub Desktop.
Save hasbro17/201d727ca6402c067dd399a8a059c32c to your computer and use it in GitHub Desktop.
UUID to base64
package main
import (
"encoding/base64"
"fmt"
"log"
"os"
uuid "github.com/satori/go.uuid"
)
func main() {
id, _ := uuid.NewV4()
fmt.Println("Original UUID\t", id.String())
enc := encode(&id)
fmt.Println("URL safe encoded", enc)
dec, err := decode(enc)
if err != nil {
log.Println("Error decoding", enc)
os.Exit(1)
}
fmt.Println("Decoded UUID\t", dec.String())
}
func encode(id *uuid.UUID) string {
return base64.RawURLEncoding.EncodeToString(id.Bytes())
}
func decode(id string) (*uuid.UUID, error) {
dec, err := base64.RawURLEncoding.DecodeString(id)
if err != nil {
return nil, err
}
decID, err := uuid.FromBytes(dec)
if err != nil {
return nil, err
}
return &decID, nil
}
@hasbro17
Copy link
Author

Output:

Original UUID	 1473cb09-59fe-4bea-94a9-7bf05a662970
URL safe encoded FHPLCVn-S-qUqXvwWmYpcA
Decoded UUID	 1473cb09-59fe-4bea-94a9-7bf05a662970

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment