Created
October 24, 2018 21:50
-
-
Save hasbro17/201d727ca6402c067dd399a8a059c32c to your computer and use it in GitHub Desktop.
UUID to base64
This file contains 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/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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output: