Documentation
¶
Overview ¶
Package codegen provides a zero-dependency library for generating random codes (numbers and letters) with configurable length. It is designed for use in fulfillment services and is thread-safe for concurrent use by multiple goroutines.
Basic usage ¶
g, err := codegen.New(
codegen.WithLength(12),
codegen.WithCharset(codegen.CharsetAlphanumericUpper),
codegen.WithPrefix("ORD-"),
)
if err != nil {
log.Fatal(err)
}
code, err := g.Generate()
// code == "ORD-A3BF9KP2XQ17"
Index ¶
Constants ¶
This section is empty.
Variables ¶
var ( // ErrInvalidLength is returned when Length is less than 1. ErrInvalidLength = errors.New("codegen: length must be greater than 0") // ErrEmptyCharset is returned when Charset is an empty string. ErrEmptyCharset = errors.New("codegen: charset must not be empty") // ErrInvalidCount is returned when the n argument passed to GenerateN is less than 1. ErrInvalidCount = errors.New("codegen: count must be greater than 0") )
Sentinel errors returned by the library. They can be compared directly using errors.Is or the == operator.
Functions ¶
func Generate ¶
Generate is a package-level convenience function that creates a temporary Generator with the provided options and generates a single code.
It is suitable for one-off code generation. If you need to generate multiple codes, create a Generator with New and reuse it instead.
Example:
code, err := codegen.Generate(
codegen.WithLength(10),
codegen.WithCharset(codegen.CharsetNumeric),
)
Types ¶
type Charset ¶
type Charset string
Charset represents the set of characters used for random code generation. You can use one of the predefined constants or define your own character set with WithCustomCharset.
const ( // CharsetNumeric contains only the digits 0-9. CharsetNumeric Charset = "0123456789" // CharsetAlphaLower contains only lowercase letters a-z. CharsetAlphaLower Charset = "abcdefghijklmnopqrstuvwxyz" // CharsetAlphaUpper contains only uppercase letters A-Z. CharsetAlphaUpper Charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" // CharsetAlpha contains both lowercase and uppercase letters (a-z, A-Z). CharsetAlpha Charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" // CharsetAlphanumeric contains digits, lowercase letters, and uppercase letters. // This is the default character set. CharsetAlphanumeric Charset = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" // CharsetAlphanumericUpper contains digits and uppercase letters only. // It is commonly used for easy-to-read order codes. CharsetAlphanumericUpper Charset = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" // CharsetAlphanumericLower contains digits and lowercase letters only. CharsetAlphanumericLower Charset = "0123456789abcdefghijklmnopqrstuvwxyz" )
type Generator ¶
type Generator struct {
// contains filtered or unexported fields
}
Generator is the primary type for generating random codes. It uses crypto/rand to provide cryptographically secure randomness, making it suitable for order codes in fulfillment systems.
Generator is safe for concurrent use by multiple goroutines. A single instance can be shared across the entire application.
func MustNew ¶
MustNew behaves like New but panics if an error occurs. It is intended for initialization during application startup, where invalid configuration should be detected immediately (fail fast).
Example:
var orderGen = codegen.MustNew(
codegen.WithLength(12),
codegen.WithCharset(codegen.CharsetAlphanumericUpper),
codegen.WithPrefix("ORD-"),
)
func New ¶
New creates and returns a new Generator with the provided options. If no options are specified, the following defaults are applied:
- Length: 8
- Charset: CharsetAlphanumeric
- Prefix: "" (empty)
- Suffix: "" (empty)
Returns an error if any option is invalid:
- ErrInvalidLength: if Length < 1
- ErrEmptyCharset: if Charset is empty
Example:
g, err := codegen.New(
codegen.WithLength(12),
codegen.WithCharset(codegen.CharsetAlphanumericUpper),
codegen.WithPrefix("ORD-"),
)
if err != nil {
log.Fatal(err)
}
func (*Generator) Generate ¶
Generate creates and returns a single random code using the current configuration. The total length of the returned string is: len(Prefix) + Length + len(Suffix).
Uses crypto/rand to ensure unpredictability. Safe for concurrent use by multiple goroutines.
Example:
code, err := g.Generate()
if err != nil {
log.Fatal(err)
}
fmt.Println(code) // "ORD-A3BF9KP2XQ17"
func (*Generator) GenerateN ¶
GenerateN creates and returns a slice containing n independently generated random codes. Since each code is generated independently, duplicates are theoretically possible, although the probability is extremely low when using a sufficiently large charset and length.
Returns ErrInvalidCount if n < 1. Safe for concurrent use by multiple goroutines.
Example:
codes, err := g.GenerateN(100)
if err != nil {
log.Fatal(err)
}
// codes contains a slice of 100 order codes
func (*Generator) Options ¶
Options returns a snapshot copy of the Generator's current configuration. Modifying the returned value does not affect the Generator.
Safe for concurrent use by multiple goroutines.
func (*Generator) SetOptions ¶
SetOptions atomically updates the Generator configuration. If any provided option is invalid, the existing configuration remains unchanged and an error is returned (no partial update).
Safe for concurrent use by multiple goroutines.
Example:
err := g.SetOptions(
codegen.WithLength(16),
codegen.WithPrefix("INV-"),
)
type Option ¶
type Option func(*Options)
Option is a functional option used to configure a Generator. Use the WithXxx helper functions to create Options and pass them to New or SetOptions.
func WithCharset ¶
WithCharset sets the character set used for random code generation. It is recommended to use one of the predefined Charset constants provided by this package.
Example:
g, _ := codegen.New(codegen.WithCharset(codegen.CharsetNumeric))
func WithCustomCharset ¶
WithCustomCharset sets a custom character set from an arbitrary string. Duplicate characters are removed to ensure a uniform distribution.
Example:
// Use only characters that are easy to distinguish visually.
g, _ := codegen.New(codegen.WithCustomCharset("23456789ABCDEFGHJKLMNPQRSTUVWXYZ"))
func WithLength ¶
WithLength sets the number of random characters for each generated code. The value must be greater than 0; otherwise, New and SetOptions will return ErrInvalidLength.
Example:
g, _ := codegen.New(codegen.WithLength(12))
func WithPrefix ¶
WithPrefix sets the static string prepended to every generated code. The Prefix is not included in Length.
Example:
g, _ := codegen.New(codegen.WithPrefix("ORD-"))
// Generates: "ORD-A3BF9KP2"
func WithSuffix ¶
WithSuffix sets the static string appended to every generated code. The Suffix is not included in Length.
Example:
g, _ := codegen.New(codegen.WithSuffix("-VN"))
// Generates: "A3BF9KP2-VN"
type Options ¶
type Options struct {
// Length is the number of random characters in each generated code,
// excluding the Prefix and Suffix.
Length int
// Charset is the character set used for random code generation.
Charset Charset
// Prefix is a static string prepended to every generated code.
Prefix string
// Suffix is a static string appended to every generated code.
Suffix string
}
Options contains the complete configuration for a Generator. All fields have valid default values provided by defaultOptions.