« Back to Index

Base62 encoding and decoding

View original Gist on GitHub

Tags: #go #uuid #serialization

main.go

// 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)
}