go-nanoid

repository·main·Indexed 23 days ago

https://github.com/matoous/go-nanoid

A Go implementation of the NanoID library for generating fast, compact, and cryptographically secure unique IDs. It provides functions like New() for default URL-friendly IDs and Generate() for custom alphabets and lengths, along with Must() and MustGenerate() variants that panic on error.

Tokens
693
Snippets
3
Records
7
Agent score
32%

What's inside go-nanoid

  1. Generate a secure URL-friendly ID with New()

    main

    Use New() to generate a secure, URL-friendly unique ID using the default alphabet (_-0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ).

    You can optionally provide a single integer argument to specify the desired length of the ID. If no argument is provided, it defaults to a length of 21.

    Errors:

    • Returns an error if a negative length is provided.
    • Returns an error if more than one argument is provided.
    • Returns an error if the underlying random number generator fails.
  2. Generate an ID with a custom alphabet and size using Generate()

    main

    Use Generate(alphabet string, size int) when you need to use a specific set of characters and a specific ID length. This is a low-level function that allows for full customization of the ID generation process.

    Errors:

    • Returns an error if the alphabet is empty or contains more than 255 characters.
    • Returns an error if the size is not a positive integer.
    • Returns an error if the underlying random number generator fails.
  3. Generate IDs without error handling using Must() and MustGenerate()

    main

    If you prefer to avoid manual error checking and are confident in your parameters, use the Must variants. These functions will panic if an error occurs during generation.

    • Must(...int) is the panic-equivalent of New().
    • MustGenerate(alphabet string, size int) is the panic-equivalent of Generate().
  4. Reference: Predefined Alphabets

    main

    The package provides several predefined alphabets for common use cases:

    NameDescription
    AlphaNumAlpha-numerical characters (abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789)
    AlphaUpper and lower case letters (abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ)
    AlphaLowerNumLower case letters and numbers (abcdefghijklmnopqrstuvwxyz0123456789)
    AlphaUpperNumUpper case letters and numbers (ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789)
    AlphaLowerLower case letters (abcdefghijklmnopqrstuvwxyz)
    AlphaUpperUpper case letters (ABCDEFGHIJKLMNOPQRSTUVWXYZ)
    NumericNumerical characters (0123456789)
    CrockfordBase32UpperCrockford uppercase base32 (0123456789ABCDEFGHJKMNPQRSTVWXYZ)
    CrockfordBase32LowerCrockford lower base32 (0123456789abcdefghjkmnpqrstvwxyz)