Last active
July 4, 2025 09:33
-
-
Save Integralist/a9d4c67d7c2c38d7a542306966fc5e23 to your computer and use it in GitHub Desktop.
Base62 encoding and decoding #go #uuid #serialization
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
// https://go.dev/play/p/IwFfNFlIq_x | |
package main | |
import ( | |
"fmt" | |
"log" | |
"github.com/dromara/dongle" | |
"github.com/google/uuid" | |
) | |
func main() { | |
id, err := uuid.NewV7() | |
if err != nil { | |
log.Fatal(err) | |
} | |
fmt.Println("UUID:", id) | |
// Convert UUID to string from its raw bytes | |
encoded := dongle.Encode. | |
FromBytes(id[:]). | |
ByBase62(). | |
ToString() | |
fmt.Println("Base62:", encoded) | |
// Decode Base62 string back to bytes | |
decoded := dongle.Decode. | |
FromString(encoded). | |
ByBase62(). | |
ToBytes() | |
// Reconstruct UUID from bytes | |
recovered, err := uuid.FromBytes(decoded) | |
if err != nil { | |
log.Fatal(err) | |
} | |
fmt.Println("Decoded UUID:", recovered) | |
} |
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
// https://go.dev/play/p/9gbyOrXVUGt | |
package main | |
import ( | |
"errors" | |
"fmt" | |
"log" | |
"strings" | |
"github.com/jxskiss/base62" | |
) | |
func main() { | |
encoded := EncodeCursor("A", "B", "C", "D", "E", "F", "G") | |
fmt.Println(encoded) | |
decoded, err := DecodeCursor(encoded) | |
if err != nil { | |
log.Fatal(err) | |
} | |
fmt.Println(decoded) | |
} | |
func EncodeCursor(values ...string) string { | |
if len(values) == 0 { | |
return "" | |
} | |
cursorStr := strings.Join(values, ",") | |
return base62.EncodeToString([]byte(cursorStr)) | |
} | |
func DecodeCursor(encodedCursor string) ([]string, error) { | |
if encodedCursor == "" { | |
return nil, nil | |
} | |
decoded, err := base62.DecodeString(encodedCursor) | |
if err != nil { | |
return nil, errors.New("invalid cursor format") | |
} | |
return strings.Split(string(decoded), ","), nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment