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

main2.go

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