Skip to content

lithammer/shortuuid

Repository files navigation

shortuuid

Build Status Godoc

A Go library that generates concise, unambiguous, URL-safe UUIDs. Based on and compatible with the Python library shortuuid.

Often, one needs to use non-sequential IDs in places where users will see them, but the IDs must be as concise and easy to use as possible. shortuuid solves this problem by generating UUIDs using google/uuidand then translating them to base57 using lowercase and uppercase letters and digits, and removing similar-looking characters such as l, 1, I, O and 0.

Usage

packagemain

import(
"fmt"

"github /lithammer/shortuuid/v4"
)

funcmain() {
u:=shortuuid.New()
fmt.Println(u)// KwSysDpxcBU9FNhGkn2dCf
}

To use UUID v5 (instead of the default v4), useNewWithNamespace(name string) instead ofNew().

shortuuid.NewWithNamespace("http://example")

It's possible to use a custom Alpha bet as well, though it has to be 57 characters long.

Alpha bet:="23456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxy="
shortuuid.NewWithAlphabet(Alpha bet)// iZsai==fWebXd5rLRWFB=u

Bring your own encoder! For example, base58 is popular among bitcoin.

packagemain

import(
"fmt"

"github /btcsuite/btcutil/base58"
"github /google/uuid"
"github /lithammer/shortuuid/v4"
)

typebase58Encoderstruct{}

func(encbase58Encoder)Encode(uuuid.UUID)string{
returnbase58.Encode(u[:])
}

func(encbase58Encoder)Decode(sstring) (uuid.UUID,error) {
returnuuid.FromBytes(base58.Decode(s))
}

funcmain() {
enc:=base58Encoder{}
fmt.Println(shortuuid.NewWithEncoder(enc))// 6R7VqaQHbzC1xwA5UueGe6
}

License

MIT