uid

package module
v1.14.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 19, 2026 License: MIT Imports: 14 Imported by: 12 modules, 32 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

UID (Unique ID)

Tests Status Go Report Card PkgGoDev

This package generates unique identifying strings. Largest attention is paid on human friendly unique identifiers (dated digits).

Installation

go get -u github.com/dracory/uid

Quick Reference / Overview Table

Below is a complete comparison of all ID generators available in this package, showing example outputs and character counts (length):

Generator Function Description / Format Length (Unformatted) Length (Formatted) Example Output
ShortID() Crockford Base32 (ts + 4-bit counter) 11 N/A sa4rc789wxg
SafeShortID() Vowel-free Base16 (ts + 4-bit counter) 14 N/A 05fr88tc139r8t
HexShortID() Hexadecimal (ts + 4-bit counter) 14 N/A 015fa88bc139a8f
ShortIDCustom(alphabet) Custom alphabet (ts + 4-bit counter) varies N/A 5fr88tc139r8t
ShortIDSec() / Safe / Hex Precision: Second (Base32 / Base16) 8 / 10 N/A 79kb780x / 3b66c3b01f
ShortIDMin() / Safe / Hex Precision: Minute (Base32 / Base16) 7 / 9 N/A 2ar3jyq / 09581dcf7
ShortIDHour() / Safe / Hex Precision: Hour (Base32 / Base16) 6 / 7 N/A 0qxf7b / 17gcdgc
ShortIDDay() / Safe / Hex Precision: Day (Base32 / Base16) 4 / 5 N/A 7myf / 3f3dh
ShortIDWeek() / Safe / Hex Precision: ISO Week (Base32 / Base16) 3 / 4 N/A 2f7 / 09g7
ShortIDMonth() / Safe / Hex Precision: Month (Base32 / Base16) 3 / 4 N/A 2ec / 09dd
ShortIDYear() / Safe / Hex Precision: Year (Base32 / Base16) 2 / 2 N/A 0s / 19
HumanUid() Dated digits (YYYYMMDD-HHMM-SSMM-MMMMNNNRRRRRRRRR) 32 35 20250831151133000012345678901234
NanoUid() Dated digits (YYYYMMDD-HHMMSS-MMMMMM-NNN) 23 26 20250831151133000012345
MicroUid() Dated digits (YYYYMMDD-HHMMSS-MMMMMM) 20 22 20250831151133000012
SecUid() Dated digits (YYYYMMDD-HHMMSS) 14 15 20250831151133
MinUid() Dated digits (YYYYMMDD-HHMM) 12 13 202508311511
HourUid() Dated digits (YYYYMMDD-HH) 10 11 2025083115
DayUid() Dated digits (YYYY-MM-DD) 8 10 20250831
WeekUid() Dated digits (YYYY-WW) 6 7 202535
MonthUid() Dated digits (YYYY-MM) 6 7 202508
Timestamp() Unix timestamp (seconds) 10 N/A 1704524414
TimestampMicro() Unix timestamp (microseconds) 16 N/A 1704524414548721
TimestampNano() Unix timestamp (nanoseconds) 19 N/A 1704524414548721308
Uuid() / UuidV4() Standard UUID v4 (random) 32 36 459e2999bd071151a23d643da42c2cc2
UuidV1() Standard UUID v1 (time-based) 32 36 6ba7b8109dad11d180b400c04fd430c8
UuidV3(...) Standard UUID v3 (MD5 name-based) 32 36 3d813cbb47fb32ba91df831e1593ac29
UuidV5(...) Standard UUID v5 (SHA-1 name-based) 32 36 21f7f8de80515b8986800195ef798b6a
UuidV6() Standard UUID v6 (time-ordered) 32 36 1ed0c9e48f7b6b2c9c3b6a6c7a9d5e12
UuidV7() Standard UUID v7 (Unix time-based) 32 36 01890f5f3d9c7a0e8a7b6c5d4e3f2a10

Usage

package main

import (
    "fmt"
    "github.com/dracory/uid"
)

func main() {
    // ShortID generates an 11-character Crockford Base32 short ID
    // Format: microsecond timestamp (int64) + 4-bit rolling counter
    shortID := uid.ShortID() // length: 11, e.g. "sa4rc789wxg"

    // SafeShortID generates a 14-character vowel-free Base16 short ID
    // (alphabet "0123456789bcdfgh" - avoids accidental English words)
    safeID := uid.SafeShortID() // length: 14, e.g. "05fh88gd139f8h"

    // HexShortID generates a 14-character lowercase hexadecimal short ID
    hexID := uid.HexShortID() // length: 14

    // ShortIDCustom encodes the same time-ordered value with a custom alphabet
    // (min 2 unique ASCII chars; panics on invalid alphabets)
    customID := uid.ShortIDCustom("0123456789abcdefghijklmnopqrstuvwxyz")

    // Helpers for validation and normalization
    ok := uid.IsShortID(shortID)           // checks length and charset
    norm := uid.NormalizeID("  " + shortID) // trims whitespace, lowercases

    // HumanUid generates a UID (32 digits)
    // Format: YYYYMMDD-HHMM-SSMM-MMMMNNNRRRRRRRRR
    human := uid.HumanUid()          // unformatted, length: 32
    humanF := uid.HumanUid(true)     // formatted (8-4-4-16), length: 35

    // NanoUid generates a UID (23 digits)
    // Format: YYYYMMDD-HHMMSS-MMMMMM-NNN
    nano := uid.NanoUid()            // unformatted, length: 23
    nanoF := uid.NanoUid(true)       // formatted (8-6-6-3), length: 26

    // MicroUid generates a UID (20 digits)
    // Format: YYYYMMDD-HHMMSS-MMMMMM
    micro := uid.MicroUid()          // unformatted, length: 20
    microF := uid.MicroUid(true)     // formatted (8-6-6), length: 22

    // SecUid generates a UID (14 digits)
    // Format: YYYYMMDD-HHMMSS
    sec := uid.SecUid()              // unformatted, length: 14
    secF := uid.SecUid(true)         // formatted (8-6), length: 15

    // Unix timestamps as strings
    ts := uid.Timestamp()            // seconds, length: 10
    tsu := uid.TimestampMicro()      // microseconds, length: 16
    tsn := uid.TimestampNano()       // nanoseconds, length: 19

    // UUIDs (implemented via standard library)
    u4 := uid.Uuid()                 // v4 unformatted, length: 32
    u4f := uid.Uuid(true)            // v4 formatted, length: 36
    v1 := uid.UuidV1()               // v1 unformatted, length: 32
    v1f := uid.UuidV1(true)          // v1 formatted, length: 36
    v3, _ := uid.UuidV3("1234567890abcdef", []byte("name"))     // v3 unformatted
    v3f, _ := uid.UuidV3("1234567890abcdef", []byte("name"), true)
    v5, _ := uid.UuidV5("1234567890abcdef", []byte("name"))     // v5 unformatted
    v5f, _ := uid.UuidV5("1234567890abcdef", []byte("name"), true)
    v6 := uid.UuidV6()               // v6 unformatted, length: 32
    v6f := uid.UuidV6(true)          // v6 formatted, length: 36
    v7 := uid.UuidV7()               // v7 unformatted, length: 32
    v7f := uid.UuidV7(true)          // v7 formatted, length: 36

    fmt.Println(shortID, safeID, hexID, customID, ok, norm,
        human, humanF, nano, nanoF, micro, microF, sec, secF,
        ts, tsu, tsn, u4, u4f, v1, v1f, v3, v3f, v5, v5f, v6, v6f, v7, v7f)

    // ID Shortening
    id := "12345678901234567890"
    short, _ := uid.ShortenBase62(id)       // "1n9XvB8P6M"
    original, _ := uid.UnshortenBase62(short) // "12345678901234567890"

    // Custom alphabet override
    customShort, _ := uid.ShortenBase16(id, "FEDCBA9876543210")
}

Supported UID Types

It supports several types of unique identifiers.

The type you want to use will usually depends on two considerations:

  1. How random you want it to be? The longer the identifier, the more the chances of collision reduce
  2. How long you want the identifier to be? The longer the identifier, reduces the readability, as well as the storage space to store it.

For most of the user cases a Micro UID (20 chars) should be fine. A human UID (32 chars) should be avoided where a human is involved as too "mind bogging" to work with.

  1. Short ID (11-14 characters)

    Format: microsecond Unix timestamp + 4-bit rolling counter, encoded in a base alphabet.

    All short IDs share one lock-free atomic generator, are time-ordered (lexicographic sort matches chronological order), and never sleep — on counter overflow the timestamp is bumped by one microsecond instead.

    • ShortID() - 11 chars, Crockford Base32 lowercase, e.g. sa4rc789wxg
    • SafeShortID() - 14 chars, vowel-free Base16 (0123456789bcdfgh), e.g. 05fh88gd139f8h
    • HexShortID() - 14 chars, standard lowercase hex
    • ShortIDCustom(alphabet) - custom alphabet (min 2 unique ASCII chars, ascending order recommended for sortable IDs)
    • ShortID<Precision>() / SafeShortID<Precision>() / HexShortID<Precision>() - fixed-width precision short IDs (Sec, Min, Hour, Day, Week, Month, Year)
    • IsShortID(id) - validates ShortID format (length + charset)
    • NormalizeID(id) - trims whitespace and lowercases

    Note: uniqueness is per-process only and IDs reveal their creation time. Suitable for sortable database keys, not for security tokens or unguessable public identifiers. ShortID() grows to 12 chars from ~2041; SafeShortID()/HexShortID() are fixed at 14 chars until ~2112.

  2. Human UID (32 digits)

    Format: YYYYMMDD-HHMM-SSMM-MMMMNNNRRRRRRRRR

    2017111908492665991498485465 (with dashes: 20171119-0849-2665-991498485465)

  3. Nano UID (23 digits)

    Format: YYYYMMDD-HHMMSS-MMMMMM-NNN

    Examples:

    20171119084926659914984 (with dashes: 20171119-084926-659914-984)

  4. Micro UID (20 digits)

    Format: YYYYMMDD-HHMMSS-MMMMMM

    Examples:

    20171119084926659914 (with dashes: 20171119-084926-659914)

  5. Seconds UID (14 digits)

    Format: YYYYMMDD-HHMMSS

    Examples:

    20171119084926 (with dashes: 20171119-084926)

  6. Digit Family UIDs (MinUid, HourUid, DayUid, WeekUid, MonthUid)

    Format: Full 4-digit year ladder (YYYYMMDDHHMM, YYYYMMDDHH, YYYYMMDD, YYYYWW, YYYYMM).

  7. Timestamp (10 digits) Unit timestamp, seconds precision

    Format: 1234567890

    Examples:

    1704524414

  8. TimestampMicro (16 digits) Unit timestamp, microseconds precision

    Format: 1234567890123456

    Examples:

    1704524414548721

  9. TimestampNano (19 digits) Unit timestamp, nanoseconds precision

    Format: 1234567890123456789

    Examples:

    1704524414548721308

  10. Uuid (32 characters) Random V4 UUID. UUID (Universally Unique IDentifier), also known as GUID (Globally Unique IDentifier)

    Format: abcdef1234567890abcdef1234567890

    Examples:

    459e2999bd071151a23d643da42c2cc2

UUID functions

UUIDs are implemented using only the Go standard library (no external deps).

  • Uuid(formatted ...bool) → version 4 (random) Examples: 550e8400e29b41d4a716446655440000 (32) • 550e8400-e29b-41d4-a716-446655440000 (36)

  • UuidV1(formatted ...bool) → version 1 (time-based) Examples: 6ba7b8109dad11d180b400c04fd430c8 (32) • 6ba7b810-9dad-11d1-80b4-00c04fd430c8 (36)

  • UuidV3(namespace string, data []byte, formatted ...bool) → version 3 (MD5 name-based) Examples: 3d813cbb47fb32ba91df831e1593ac29 (32) • 3d813cbb-47fb-32ba-91df-831e1593ac29 (36)

  • UuidV4(formatted ...bool) → version 4 (random) Examples: 550e8400e29b41d4a716446655440000 (32) • 550e8400-e29b-41d4-a716-446655440000 (36)

  • UuidV5(namespace string, data []byte, formatted ...bool) → version 5 (SHA-1 name-based) Examples: 21f7f8de80515b8986800195ef798b6a (32) • 21f7f8de-8051-5b89-8680-0195ef798b6a (36)

  • UuidV6(formatted ...bool) → version 6 (time-ordered) Examples: 1ed0c9e48f7b6b2c9c3b6a6c7a9d5e12 (32) • 1ed0c9e4-8f7b-6b2c-9c3b-6a6c7a9d5e12 (36)

  • UuidV7(formatted ...bool) → version 7 (Unix time-based) Examples: 01890f5f3d9c7a0e8a7b6c5d4e3f2a10 (32) • 01890f5f-3d9c-7a0e-8a7b-6c5d4e3f2a10 (36)

ID Shortening

The package provides functions to shorten numeric string IDs into more compact representations using various base encodings. All shortening and unshortening functions accept an optional custom alphabet parameter (e.g. ShortenBase16(id, alphabet...)). If omitted, the default alphabet for that base encoding is used.

Method Encoding Alphabet Case-Sensitive Human-Facing
ShortenBase16 Hexadecimal 0-9, a-f No No
ShortenBase32 Base32 (RFC 4648) a-z, 2-7 No Yes
ShortenCrockford Crockford Base32 0-9, A-Z (exc. I,L,O,U) No (Normalizes) Best
ShortenBase36 Base36 0-9, a-z No Yes
ShortenBase58 Base58 (Bitcoin) 1-9, A-Z, a-z (exc. 0,O,I,l) Yes Better
ShortenBase62 Base62 0-9, A-Z, a-z Yes No
ShortenBase64 Base64 (URL-safe) A-Z, a-z, 0-9, -, _ Yes No
ShortenZBase32 z-base-32 y,b,n,d,r,f,g,8,e,j... No Good

Example:

id := "12345678901234567890"
short, _ := uid.ShortenBase62(id)       // "1n9XvB8P6M"
original, _ := uid.UnshortenBase62(short) // "12345678901234567890"

// Using custom alphabet
customShort, _ := uid.ShortenBase16(id, "FEDCBA9876543210")
customOriginal, _ := uid.UnshortenBase16(customShort, "FEDCBA9876543210")
Comparison Table

Using a sample HumanUid as input:

Operation Result Length
Original HumanUid 20260116055547619570214289007495 32
ShortenBase16 ffb7f7358fa8ad8f0adb27e387 26
ShortenBase32 p7n7xgwh2rlmpblnspy4h 21
ShortenCrockford FZDZQ6P7THBCF1BDJFRW7 21
ShortenZBase32 x9p9zgs84tmcxbmp1xah8 21
ShortenBase36 1ik90wbiqnpjge668igef 21
ShortenBase58 NJMxnyUkCcK1mbKaR4 18
ShortenBase62 6qz9D7Ih28OnrKPXj5 18
ShortenBase64 D_t_c1j6itjwrbJ-OH 18

Using a sample SecUid as input:

Operation Result Length
Original SecUid 20260116060140 14
ShortenBase16 126d2d0557ec 12
ShortenBase32 snuwqkv7m 9
ShortenCrockford JDMPGANZC 9
ShortenZBase32 1pwsoki9c 9
ShortenBase36 76jda01yk 9
ShortenBase58 ABCY5ZqV 8
ShortenBase62 5kgp4HO8 8
ShortenBase64 Em0tBVfs 8

Using a sample MicroUid as input:

Operation Result Length
Original MicroUid 20260116060209548481 20
ShortenBase16 1192a6436ccfa0cc1 17
ShortenBase32 rskteg3gpudgb 13
ShortenCrockford HJAK46V6FM361 13
ShortenZBase32 t1kurg5gxwdgb 13
ShortenBase36 49xd7r0cxnoht 13
ShortenBase58 p2fBzoDdpyN 11
ShortenBase62 O8dXskGYQfx 11
ShortenBase64 RkqZDbM-gzB 11

Using a sample NanoUid as input:

Operation Result Length
Original NanoUid 20260116060418792413315 23
ShortenBase16 44a4d97764168aad883 19
ShortenBase32 rfe3f3wifukvwed 15
ShortenCrockford H54V5VP85MANP43 15
ShortenZBase32 tfr5f5sefwkisrd 15
ShortenBase36 3arqv3acnfg822r 15
ShortenBase58 EyqbSbbMe7wtW 13
ShortenBase62 6HLJqV3vQ4U1j 13
ShortenBase64 ESk2XdkFoqtiD 13

Using a sample Timestamp (seconds) as input:

Operation Result Length
Original Timestamp 1768543518 10
ShortenBase16 6969d51e 8
ShortenBase32 buwtvi6 7
ShortenCrockford 1MPKN8Y 7
ShortenZBase32 bwsuie6 7
ShortenBase36 t8y0wu 6
ShortenBase58 3hHFNd 6
ShortenBase62 1vgcxS 6
ShortenBase64 BpadUe 6

Using a sample TimestampMicro (microseconds) as input:

Operation Result Length
Original TimestampMicro 1768543534819239 16
ShortenBase16 6487b2129a7a7 13
ShortenBase32 bsipmqstj5h 11
ShortenCrockford 1J8FCGJK9X7 11
ShortenZBase32 b1exco1uj78 11
ShortenBase36 hew9om6uuf 10
ShortenBase58 Eoye75bHY 9
ShortenBase62 86CCRTsQx 9
ShortenBase64 GSHshKaen 9

Using a sample TimestampNano (nanoseconds) as input:

Operation Result Length
Original TimestampNano 1768543548681502200 19
ShortenBase16 188b20fcc4f83df8 16
ShortenBase32 brcza7tcpqppy 13
ShortenCrockford 1H2S0ZK2FGFFR 13
ShortenZBase32 btn3y9unxoxxa 13
ShortenBase36 dfpsd65np7nc 12
ShortenBase58 576wZ6w7qyR 11
ShortenBase62 26dwmwO2cbw 11
ShortenBase64 BiLIPzE-D34 11

Change Log

2026.10.15 - Reworked short ID generators: lock-free CAS state, SafeShortID()/HexShortID() widened to 14 chars, ShortIDCustom() alphabet validation, IsShortID() charset check

2026.09.20 - Added ShortID()

2026.01.16 - Add ID shortening and unshortening (Base16,32,36,58,62,64,Crockford,ZBase32)

2025.09.01 - Add optional hyphen formatting

2025.08.31 - Move UUID functions/tests into separate files

2024.01.06 - Added Timestamp and Uuid functions

2021.12.19 - Master branch changed to main

2021.12.19 - Added tests

Similar Packages

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrInvalidByte  = errors.New("character not in alphabet")
	ErrInvalidInput = errors.New("uid: invalid numeric input")
)

Functions

func DayUid added in v1.14.0

func DayUid(formatted ...bool) string

DayUid generates an 8-character time-based ID to day precision.

Format: YYYYMMDD

Example (unformatted): 20250831 (length: 8) Example (formatted): 2025-08-31 (length: 10)

Parameters: - formatted: when true, include hyphens in groups 4-2-2 (length becomes 10)

Returns: - An 8-character numeric string representing UTC date to the day

func HexShortID added in v1.12.0

func HexShortID() string

HexShortID generates a standard 14-character lowercase hexadecimal short ID. Uses the same timestamp + 4-bit rolling counter logic as SafeShortID, formatted with the standard lowercase hex alphabet "0123456789abcdef".

Returns:

  • A 14-character lowercase hexadecimal string.

func HexShortIDDay added in v1.14.0

func HexShortIDDay() string

HexShortIDDay creates a 5-character Hex Base16 short ID to day precision.

func HexShortIDHour added in v1.14.0

func HexShortIDHour() string

HexShortIDHour creates a 7-character Hex Base16 short ID to hour precision.

func HexShortIDMin added in v1.14.0

func HexShortIDMin() string

HexShortIDMin creates a 9-character Hex Base16 short ID to minute precision.

func HexShortIDMonth added in v1.14.0

func HexShortIDMonth() string

HexShortIDMonth creates a 4-character Hex Base16 short ID to month precision.

func HexShortIDSec added in v1.14.0

func HexShortIDSec() string

HexShortIDSec creates a 10-character Hex Base16 short ID to second precision.

func HexShortIDWeek added in v1.14.0

func HexShortIDWeek() string

HexShortIDWeek creates a 4-character Hex Base16 short ID to ISO week precision.

func HexShortIDYear added in v1.14.0

func HexShortIDYear() string

HexShortIDYear creates a 2-character Hex Base16 short ID to year precision.

func HourUid added in v1.14.0

func HourUid(formatted ...bool) string

HourUid generates a 10-character time-based ID to hour precision.

Format: YYYYMMDDHH

Example (unformatted): 2025083115 (length: 10) Example (formatted): 20250831-15 (length: 11)

Parameters: - formatted: when true, include hyphens in groups 8-2 (length becomes 11)

Returns: - A 10-character numeric string representing UTC date/time to the hour

func HumanUid

func HumanUid(formatted ...bool) string

HumanUid generates a 32-character time-prefixed unique ID.

Format (conceptual): YYYYMMDDHHMMSSMMMMMMM + random suffix, truncated to 32.

Example (unformatted): 20250831151133000012345678901234 (length: 32) Example (formatted): 20171119-0849-2665-991498485465 (length: 35)

Parameters: - formatted: when true, include hyphens in groups 8-4-4-16 (length becomes 35)

Returns: - A 32-character uppercase numeric string suitable for human-readable IDs

func IsShortID added in v1.10.0

func IsShortID(id string) bool

IsShortID checks whether the given string matches the format produced by ShortID: the correct length and only lowercase Crockford Base32 characters. It does NOT cover the SafeShortID/HexShortID/ShortIDCustom formats.

Parameters:

  • id: the ID string to check.

Returns:

  • true if id looks like a ShortID() output; false otherwise.

Example:

  • ok := uid.IsShortID("sa4rc789wxg") // true

func MicroUid

func MicroUid(formatted ...bool) string

MicroUid generates a 20-character time-prefixed unique ID.

Format (conceptual): YYYYMMDDHHMMSSMMMMMMM + random suffix, truncated to 20.

Example (unformatted): 20250831151133000012 (length: 20) Example (formatted): 20171119-084926-659914 (length: 22)

Parameters: - formatted: when true, include hyphens in groups 8-6-6 (length becomes 22)

Returns: - A 20-character numeric string

func MinUid added in v1.14.0

func MinUid(formatted ...bool) string

MinUid generates a 12-character time-based ID to minute precision.

Format: YYYYMMDDHHMM

Example (unformatted): 202508311511 (length: 12) Example (formatted): 20250831-1511 (length: 13)

Parameters: - formatted: when true, include hyphens in groups 8-4 (length becomes 13)

Returns: - A 12-character numeric string representing UTC date/time to the minute

func MonthUid added in v1.14.0

func MonthUid(formatted ...bool) string

MonthUid generates a 6-character time-based ID to month precision.

Format: YYYYMM

Example (unformatted): 202508 (length: 6) Example (formatted): 2025-08 (length: 7)

Parameters: - formatted: when true, include hyphens in groups 4-2 (length becomes 7)

Returns: - A 6-character numeric string representing UTC date to the month

func NanoUid

func NanoUid(formatted ...bool) string

NanoUid generates a 23-character time-prefixed unique ID.

Format (conceptual): YYYYMMDDHHMMSSMMMMMMM + random suffix, truncated to 23.

Example (unformatted): 20250831151133000012345 (length: 23) Example (formatted): 20171119-084926-659914-984 (length: 26)

Parameters: - formatted: when true, include hyphens in groups 8-6-6-3 (length becomes 26)

Returns: - A 23-character numeric string

func NormalizeID added in v1.10.0

func NormalizeID(id string) string

NormalizeID normalizes an ID to lowercase and trims whitespace for consistent lookups.

Parameters:

  • id: the ID string to normalize.

Returns:

  • The trimmed, lowercased ID.

Example:

  • norm := uid.NormalizeID(" SA4RC789WXG ") // "sa4rc789wxg"

func SafeShortID added in v1.12.0

func SafeShortID() string

SafeShortID generates a fixed 14-character lowercase short ID using a vowel-free Base 16 alphabet. Core logic: microsecond timestamp shifted left by 4 bits, combined with a 4-bit rolling counter, produced by nextShortIDValue. Alphabet (Base 16, vowel-free): "0123456789bcdfgh". Every letter of standard hex is shifted to the next sequential consonant ('a'->'b', 'b'->'c', 'c'->'d', 'd'->'f', 'e'->'g', 'f'->'h') to avoid generating accidental English words; this greatly reduces but does not eliminate them (leet-speak like "b00b" is still reachable). The alphabet is in ascending byte order, so generated IDs sort chronologically.

Returns:

  • A 14-character lowercase string (e.g. "05fh88gd139f8h").

func SafeShortIDDay added in v1.14.0

func SafeShortIDDay() string

SafeShortIDDay creates a 5-character Safe Base16 short ID to day precision.

func SafeShortIDHour added in v1.14.0

func SafeShortIDHour() string

SafeShortIDHour creates a 7-character Safe Base16 short ID to hour precision.

func SafeShortIDMin added in v1.14.0

func SafeShortIDMin() string

SafeShortIDMin creates a 9-character Safe Base16 short ID to minute precision.

func SafeShortIDMonth added in v1.14.0

func SafeShortIDMonth() string

SafeShortIDMonth creates a 4-character Safe Base16 short ID to month precision.

func SafeShortIDSec added in v1.14.0

func SafeShortIDSec() string

SafeShortIDSec creates a 10-character Safe Base16 short ID to second precision.

func SafeShortIDWeek added in v1.14.0

func SafeShortIDWeek() string

SafeShortIDWeek creates a 4-character Safe Base16 short ID to ISO week precision.

func SafeShortIDYear added in v1.14.0

func SafeShortIDYear() string

SafeShortIDYear creates a 2-character Safe Base16 short ID to year precision.

func SecUid

func SecUid(formatted ...bool) string

SecUid generates a 14-character time-based ID.

Format: YYYYMMDDHHMMSS

Example (unformatted): 20250831151133 (length: 14) Example (formatted): 20171119-084926 (length: 15)

Parameters: - formatted: when true, include hyphens in groups 8-6 (length becomes 15)

Returns: - A 14-character numeric string representing UTC date/time to the second

func Short added in v1.9.0

func Short(id string) (string, error)

Short converts a numeric ID string to a short, human-friendly representation using Base58.

Parameters: - id: A numeric string ID (may contain hyphens which are ignored).

Returns: - A shortened string representation, or an error if input is invalid.

func ShortID added in v1.11.0

func ShortID() string

ShortID creates a new 11-character lowercase short ID. It encodes the current microsecond timestamp in Crockford Base32. Thread-safe via a lock-free CAS loop; survives backwards clock steps.

Business Logic:

  • Uses time.Now().UnixMicro() as the uniqueness base.
  • Maintains a package-level atomic (timestamp << 4) | counter state.
  • Counter increments while the timestamp does not advance; when it would exceed 15, the timestamp is bumped by one microsecond instead of sleeping, so callers never stall and IDs never regress.
  • Packs timestamp and counter into a single int64: (ts << 4) | counter.
  • Encodes the composite value with a lowercase Crockford Base32 alphabet.

Notes:

  • Uniqueness is per-process only: two processes generating IDs in the same microsecond can collide. The IDs are also predictable and reveal their creation time, so they are suitable for sortable database keys but NOT for security tokens or unguessable public identifiers.

Returns:

  • An 11-character lowercase string (e.g. "sa4rc789wxg").

Example:

  • id := uid.ShortID() // "sa4rc789wxg"

func ShortIDCustom added in v1.12.0

func ShortIDCustom(alphabet string) string

ShortIDCustom generates a time-ordered short ID using a user-provided custom alphabet string. Encodes the combined (timestamp << 4) | counter value using modulo arithmetic against the length of the provided alphabet.

Parameters:

  • alphabet: a string of at least 2 unique single-byte (ASCII) characters. If empty, defaults to "0123456789abcdef". For IDs that sort chronologically the characters must be in ascending byte order. Panics on an invalid alphabet.

Returns:

  • A time-ordered short ID encoded with the custom alphabet.

func ShortIDDay added in v1.14.0

func ShortIDDay() string

ShortIDDay creates a 4-character Crockford Base32 short ID to day precision (YYMMDD).

func ShortIDHour added in v1.14.0

func ShortIDHour() string

ShortIDHour creates a 6-character Crockford Base32 short ID to hour precision (YYMMDDHH).

func ShortIDMin added in v1.14.0

func ShortIDMin() string

ShortIDMin creates a 7-character Crockford Base32 short ID to minute precision (YYMMDDHHMM).

func ShortIDMonth added in v1.14.0

func ShortIDMonth() string

ShortIDMonth creates a 3-character Crockford Base32 short ID to month precision (YYMM).

func ShortIDSec added in v1.14.0

func ShortIDSec() string

ShortIDSec creates an 8-character Crockford Base32 short ID to second precision (YYMMDDHHMMSS).

func ShortIDWeek added in v1.14.0

func ShortIDWeek() string

ShortIDWeek creates a 3-character Crockford Base32 short ID to ISO week precision (YYWW).

func ShortIDYear added in v1.14.0

func ShortIDYear() string

ShortIDYear creates a 2-character Crockford Base32 short ID to year precision (YY).

func ShortenBase16 added in v1.9.0

func ShortenBase16(id string, alphabet ...string) (string, error)

ShortenBase16 converts a numeric string ID to a base16 (hexadecimal) string.

Benefits: - Standard hexadecimal representation. - Compatible with most systems and easily parsed.

Drawbacks: - Least compact representation; results in the longest strings.

Example: ShortenBase16("1234567890") -> "499602d2"

Parameters: - id: A numeric string representation of a positive integer. - alphabet: Optional custom alphabet to override default base16 alphabet.

Returns: - A base16 encoded string.

func ShortenBase32 added in v1.9.0

func ShortenBase32(id string, alphabet ...string) (string, error)

ShortenBase32 converts a numeric string ID to a base32 string (RFC 4648).

Benefits: - Case-insensitive and safe for filesystems. - Compact representation using only 32 characters.

Drawbacks: - Less compact than Base58/Base62. - Includes 'l' and 'i' which can be visually similar in some fonts.

Example: ShortenBase32("1234567890") -> "gnm6fsq"

Parameters: - id: A numeric string representation of a positive integer. - alphabet: Optional custom alphabet to override default base32 alphabet.

Returns: - A base32 string.

func ShortenBase36 added in v1.9.0

func ShortenBase36(id string, alphabet ...string) (string, error)

ShortenBase36 converts a numeric string ID to a base36 string.

Benefits: - Uses all digits and lowercase letters (0-9, a-z). - Case-insensitive and widely used for compact IDs.

Drawbacks: - Includes 'l', '1', 'o', and '0', which can be visually confusing.

Example: ShortenBase36("1234567890") -> "kf12oi"

Parameters: - id: A numeric string representation of a positive integer. - alphabet: Optional custom alphabet to override default base36 alphabet.

Returns: - A base36 string.

func ShortenBase58 added in v1.9.0

func ShortenBase58(id string, alphabet ...string) (string, error)

ShortenBase58 converts a numeric string ID to a base58 string.

Benefits: - Human-friendly: avoids ambiguous characters like 0, O, I, and l. - No non-alphanumeric characters, making it safe for double-clicking to select.

Drawbacks: - Case-sensitive; requires exact casing for decoding.

Example: ShortenBase58("1234567890") -> "2V6G2p"

Parameters: - id: A numeric string representation of a positive integer. - alphabet: Optional custom alphabet to override default base58 alphabet.

Returns: - A base58 string.

func ShortenBase62 added in v1.9.0

func ShortenBase62(id string, alphabet ...string) (string, error)

ShortenBase62 converts a numeric string ID to a base62 string.

Benefits: - Maximum density using all standard alphanumeric characters (0-9, A-Z, a-z). - Very compact and widely supported by URL shorteners.

Drawbacks: - Case-sensitive, prone to manual entry errors. - Includes visually similar characters (e.g., 'I', 'l', '1', 'O', '0').

Example: ShortenBase62("1234567890") -> "1LY7vk"

Parameters: - id: A numeric string representation of a positive integer. - alphabet: Optional custom alphabet to override default base62 alphabet.

Returns: - A base62 string.

func ShortenBase64 added in v1.9.0

func ShortenBase64(id string, alphabet ...string) (string, error)

ShortenBase64 converts a numeric string ID to a URL-safe base64 string.

Benefits: - Extremely compact representation. - Safe for use in URLs (uses '-' and '_' instead of '+' and '/').

Drawbacks: - Case-sensitive, which can lead to errors if manually typed. - Contains visually similar characters (e.g., 'O' and '0', 'I' and 'l'). - Includes '-' and '_', which can interfere with double-click selection in some UIs. - Not recommended for human-facing IDs; consider Base58 or Crockford instead.

Example: ShortenBase64("1234567890") -> "BJlg8u"

Parameters: - id: A numeric string representation of a positive integer. - alphabet: Optional custom alphabet to override default base64 alphabet.

Returns: - A URL-safe base64 string.

func ShortenCrockford added in v1.9.0

func ShortenCrockford(id string, alphabet ...string) (string, error)

ShortenCrockford converts a numeric string ID to a Crockford Base32 string.

Benefits: - Highly human-readable and designed to avoid common transcription errors. - Excludes ambiguous characters like I, L, O, and U.

Drawbacks: - Less compact than Base62/Base64.

Example: ShortenCrockford("1234567890") -> "14MM0M"

Parameters: - id: A numeric string representation of a positive integer. - alphabet: Optional custom alphabet to override default Crockford alphabet.

Returns: - A Crockford Base32 string.

func ShortenZBase32 added in v1.9.0

func ShortenZBase32(id string, alphabet ...string) (string, error)

ShortenZBase32 converts a numeric string ID to a z-base-32 string.

Benefits: - Optimized for human readability and memorability. - Alphabet is designed to put easiest-to-recognize characters in most-used positions.

Drawbacks: - Non-standard alphabet; not as widely supported as RFC 4648 Base32.

Example: ShortenZBase32("1234567890") -> "4pk9xyo"

Parameters: - id: A numeric string representation of a positive integer. - alphabet: Optional custom alphabet to override default z-base-32 alphabet.

Returns: - A z-base-32 string.

func Timestamp

func Timestamp() string

Timestamp returns the current Unix timestamp in seconds as a string.

Example: 1725111153 (length: 10)

Parameters: - None

Returns: - Unix timestamp in seconds (base-10 string)

func TimestampMicro

func TimestampMicro() string

TimestampMicro returns the current Unix timestamp in microseconds as a string.

Example: 1725111153123456 (length: 16)

Parameters: - None

Returns: - Unix timestamp in microseconds (base-10 string)

func TimestampNano

func TimestampNano() string

TimestampNano returns the current Unix timestamp in nanoseconds as a string.

Example: 1725111153123456789 (length: 19)

Parameters: - None

Returns: - Unix timestamp in nanoseconds (base-10 string)

func Unshort added in v1.9.0

func Unshort(s string) (string, error)

Unshort converts a shortened string (Base58) back to its original numeric ID.

Parameters: - s: A shortened string ID (Base58).

Returns: - The original numeric string ID, or an error if decoding fails.

func UnshortenBase16 added in v1.9.0

func UnshortenBase16(s string, alphabet ...string) (string, error)

UnshortenBase16 converts a base16 (hexadecimal) string back to its original numeric string ID.

Example: UnshortenBase16("499602d2") -> "1234567890"

Parameters: - s: A hexadecimal string. - alphabet: Optional custom alphabet to override default base16 alphabet.

Returns: - The original numeric string ID, or an error if invalid characters are encountered.

func UnshortenBase32 added in v1.9.0

func UnshortenBase32(s string, alphabet ...string) (string, error)

UnshortenBase32 converts a base32 string back to its original numeric string ID.

Example: UnshortenBase32("gnm6fsq") -> "1234567890"

Parameters: - s: A base32 string (case-insensitive when using default alphabet). - alphabet: Optional custom alphabet to override default base32 alphabet.

Returns: - The original numeric string ID, or an error if invalid characters are encountered.

func UnshortenBase36 added in v1.9.0

func UnshortenBase36(s string, alphabet ...string) (string, error)

UnshortenBase36 converts a base36 string back to its original numeric string ID.

Example: UnshortenBase36("kf12oi") -> "1234567890"

Parameters: - s: A base36 string (case-insensitive when using default alphabet). - alphabet: Optional custom alphabet to override default base36 alphabet.

Returns: - The original numeric string ID, or an error if invalid characters are encountered.

func UnshortenBase58 added in v1.9.0

func UnshortenBase58(s string, alphabet ...string) (string, error)

UnshortenBase58 converts a base58 string back to its original numeric string ID.

Example: UnshortenBase58("2V6G2p") -> "1234567890"

Parameters: - s: A base58 string. - alphabet: Optional custom alphabet to override default base58 alphabet.

Returns: - The original numeric string ID, or an error if invalid characters are encountered.

func UnshortenBase62 added in v1.9.0

func UnshortenBase62(s string, alphabet ...string) (string, error)

UnshortenBase62 converts a base62 string back to its original numeric string ID.

Example: UnshortenBase62("1LY7vk") -> "1234567890"

Parameters: - s: A base62 string. - alphabet: Optional custom alphabet to override default base62 alphabet.

Returns: - The original numeric string ID, or an error if invalid characters are encountered.

func UnshortenBase64 added in v1.9.0

func UnshortenBase64(s string, alphabet ...string) (string, error)

UnshortenBase64 converts a URL-safe base64 string back to its original numeric string ID.

Example: UnshortenBase64("BJlg8u") -> "1234567890"

Parameters: - s: A URL-safe base64 string. - alphabet: Optional custom alphabet to override default base64 alphabet.

Returns: - The original numeric string ID, or an error if invalid characters are encountered.

func UnshortenCrockford added in v1.9.0

func UnshortenCrockford(s string, alphabet ...string) (string, error)

UnshortenCrockford converts a Crockford Base32 string back to its original numeric string ID.

Features: - Supports normalization (converts to uppercase, removes hyphens, maps visually similar characters) when using default alphabet.

Example: UnshortenCrockford("14MM0M") -> "1234567890"

Parameters: - s: A Crockford Base32 string. - alphabet: Optional custom alphabet to override default Crockford alphabet.

Returns: - The original numeric string ID, or an error if invalid characters are encountered.

func UnshortenZBase32 added in v1.9.0

func UnshortenZBase32(s string, alphabet ...string) (string, error)

UnshortenZBase32 converts a z-base-32 string back to its original numeric string ID.

Example: UnshortenZBase32("4pk9xyo") -> "1234567890"

Parameters: - s: A z-base-32 string (case-insensitive when using default alphabet). - alphabet: Optional custom alphabet to override default z-base-32 alphabet.

Returns: - The original numeric string ID, or an error if invalid characters are encountered.

func Uuid

func Uuid(formatted ...bool) string

Uuid returns a random UUID (version 4) without hyphens.

Example: 550e8400e29b41d4a716446655440000 (length: 32)

https://en.wikipedia.org/wiki/Universally_unique_identifier#Version_4_(random)

Parameters: - formatted: when true, include hyphens

Returns: - A random UUID (version 4) without hyphens

func UuidV1

func UuidV1(formatted ...bool) string

UuidV1 returns a version 1 (time-based) UUID without hyphens.

Example: 6ba7b8109dad11d180b400c04fd430c8 (length: 32)

https://en.wikipedia.org/wiki/Universally_unique_identifier#Versions_1_and_6_(date-time_and_MAC_address)

Parameters: - formatted: when true, include hyphens

Returns: - The UUID v1 as a string

func UuidV3

func UuidV3(namespace string, data []byte, formatted ...bool) (string, error)

UuidV3 returns a version 3 (MD5 name-based) UUID. Provide a 16-byte namespace UUID and arbitrary data.

Example (no hyphens): 3d813cbb47fb32ba91df831e1593ac29 (length: 32)

https://en.wikipedia.org/wiki/Universally_unique_identifier#Versions_3_and_5_(namespace_name-based)

Parameters: - namespace: a 16-byte UUID (as bytes) used as the namespace - data: the name bytes to hash - formatted: when true, include hyphens

Returns: - The UUID v3 as a string, or an error

func UuidV4

func UuidV4(formatted ...bool) string

UuidV4 returns a random UUID (version 4) without hyphens.

Example: 550e8400e29b41d4a716446655440000 (length: 32)

https://en.wikipedia.org/wiki/Universally_unique_identifier#Version_4_(random)

Parameters: - formatted: when true, include hyphens

Returns: - A random UUID (version 4) without hyphens

func UuidV5

func UuidV5(namespace string, data []byte, formatted ...bool) (string, error)

UuidV5 returns a version 5 (SHA-1 name-based) UUID. Provide a 16-byte namespace UUID and arbitrary data.

Example (no hyphens): 21f7f8de80515b8986800195ef798b6a (length: 32)

https://en.wikipedia.org/wiki/Universally_unique_identifier#Versions_3_and_5_(namespace_name-based)

Parameters: - namespace: a 16-byte UUID (as bytes) used as the namespace - data: the name bytes to hash - formatted: when true, include hyphens

Returns: - The UUID v5 as a string, or an error

func UuidV6

func UuidV6(formatted ...bool) string

UuidV6 returns a version 6 (time-ordered) UUID without hyphens.

Example: 1ed0c9e48f7b6b2c9c3b6a6c7a9d5e12 (length: 32)

Draft: https://en.wikipedia.org/wiki/Universally_unique_identifier#Versions_1_and_6_(date-time_and_MAC_address)

Parameters: - formatted: when true, include hyphens

Returns: - A UUID v6 (time-ordered) without hyphens

func UuidV7

func UuidV7(formatted ...bool) string

UuidV7 returns a version 7 (Unix time-based) UUID without hyphens.

Example: 01890f5f3d9c7a0e8a7b6c5d4e3f2a10 (length: 32)

Draft: https://en.wikipedia.org/wiki/Universally_unique_identifier#Version_7_(timestamp_and_random)

Parameters: - formatted: when true, include hyphens

Returns: - A UUID v7 (Unix time-based) without hyphens

func WeekUid added in v1.14.0

func WeekUid(formatted ...bool) string

WeekUid generates a 6-character time-based ID to ISO week precision.

Format: YYYYWW

Example (unformatted): 202535 (length: 6) Example (formatted): 2025-35 (length: 7)

Parameters: - formatted: when true, include hyphens in groups 4-2 (length becomes 7)

Returns: - A 6-character numeric string representing UTC ISO year and week

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址