Documentation
¶
Overview ¶
Package nanoid generates compact, URL-safe, cryptographically random identifiers, a Go port of the npm "nanoid" package. nanoid is a popular modern alternative to UUIDs: the identifiers are shorter, need no hyphenation or special encoding to travel safely in URLs, and are produced from a cryptographically secure random source. This implementation uses only the Go standard library, drawing its randomness from crypto/rand.
You use this package whenever you need unique, unguessable, opaque tokens — database primary keys, short links, session or resource identifiers, file names — and want something more compact and URL-friendly than a canonical UUID string. Because the bytes come from a CSPRNG the ids are suitable for contexts where predictability would be a security problem, and because the default alphabet is URL- and filename-safe they can be dropped into a path or query string without escaping.
Internally an id is built by sampling random bytes and mapping them onto the alphabet with an unbiased mask-and-reject scheme. A bit mask the size of the smallest power of two that covers the alphabet is applied to each random byte; values that fall outside the alphabet range are discarded and more randomness is drawn, which keeps every character equally likely rather than skewing toward the start of the alphabet the way a naive modulo would. Bytes are requested from crypto/rand in batches sized to make rejections cheap.
The default alphabet is the 64-character URL-safe set A–Z, a–z, 0–9, "_" and "-" exposed as DefaultAlphabet, and the default length is DefaultSize (21), which gives a collision probability comparable to a v4 UUID. New returns an id with those defaults; NewSize keeps the default alphabet but lets you choose the length; and Custom lets you supply both a custom alphabet and a custom size, for example to restrict ids to lowercase hex or to trade length for a larger keyspace.
The inputs are validated rather than silently coerced: a size that is zero or negative, or an alphabet whose length is outside 1..256, produces an error. Note that a shorter id or a smaller alphabet increases the chance of collisions, so those are trade-offs the caller makes deliberately. Compared with the Node original the generation algorithm and default alphabet and size are the same, and the output is the same kind of string; the main differences are that errors (including any failure to read from the system RNG) are returned as Go error values instead of thrown, and that each generated value is inherently random, so callers should test properties such as length and alphabet membership rather than exact output.
Index ¶
Examples ¶
Constants ¶
const DefaultAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-"
DefaultAlphabet is the URL-safe alphabet used by nanoid.
const DefaultSize = 21
DefaultSize is the default id length.
Variables ¶
This section is empty.
Functions ¶
func Custom ¶
Custom returns a nanoid using the given alphabet and size, sampling bytes from crypto/rand with an unbiased mask/reject method.
Example ¶
ExampleCustom supplies both a custom alphabet and a custom size, restricting the id to lowercase hexadecimal digits. The unbiased mask-and-reject sampler ensures every character of the alphabet is equally likely despite the alphabet length not being a power of two. The example verifies the length is 16 and that every character is a valid hex digit. Custom is the entry point for domain constraints such as case-insensitive tokens or a reduced character set.
package main
import (
"fmt"
"strings"
"github.com/malcolmston/express/nanoid"
)
func main() {
id, err := nanoid.Custom("0123456789abcdef", 16)
if err != nil {
panic(err)
}
fmt.Println(len(id))
fmt.Println(strings.Trim(id, "0123456789abcdef") == "")
}
Output: 16 true
func New ¶
New returns a nanoid using the default alphabet and size.
Example ¶
ExampleNew generates an identifier with the package defaults: the 64-character URL-safe alphabet and a length of 21. Because the bytes come from crypto/rand the value is different on every run, so the example asserts on its properties rather than printing the id itself. It confirms the id is exactly DefaultSize characters long and that every character is drawn from DefaultAlphabet, which is what makes the id safe to drop into a path or query string without escaping. The strings.Trim call removes all alphabet characters; an empty remainder means no character fell outside the alphabet.
package main
import (
"fmt"
"strings"
"github.com/malcolmston/express/nanoid"
)
func main() {
id, err := nanoid.New()
if err != nil {
panic(err)
}
fmt.Println(len(id) == nanoid.DefaultSize)
fmt.Println(strings.Trim(id, nanoid.DefaultAlphabet) == "")
}
Output: true true
func NewSize ¶
NewSize returns a nanoid using the default alphabet and the given size.
Example ¶
ExampleNewSize keeps the default URL-safe alphabet but chooses a custom length, here 10 characters. A shorter id has a smaller keyspace and therefore a higher collision probability, so the length is a deliberate trade-off the caller makes against compactness. As with New the value is random, so the example prints the length rather than the id. This is the right entry point when the default 21-character id is longer than a use case needs.
package main
import (
"fmt"
"github.com/malcolmston/express/nanoid"
)
func main() {
id, err := nanoid.NewSize(10)
if err != nil {
panic(err)
}
fmt.Println(len(id))
}
Output: 10
Types ¶
This section is empty.