Documentation
¶
Overview ¶
Package gen provides string generators, used across the devkit wherever an identifier has to be produced.
A StringGenerator is a function, so it is injected rather than called directly - which is what makes the identifier deterministic in tests:
middleware := httpserver.TraceID(gen.UUIDGenerator()) // production middleware := httpserver.TraceID(gen.SequenceGenerator()) // tests
UUIDGenerator produces random UUIDv4 strings. ULIDGenerator produces ULIDs, which sort lexicographically by creation time - useful when the identifier doubles as a sort key. SequenceGenerator counts from one; it is safe to call from multiple goroutines, but the sequence restarts with each generator, so it is meant for tests rather than for identifiers that must be unique across processes.
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type StringGenerator ¶
type StringGenerator func() string
StringGenerator produces a new string on every call. It is a function type so that a caller can inject a deterministic generator in tests where production code uses a random one.
func SequenceGenerator ¶
func SequenceGenerator() StringGenerator
SequenceGenerator returns a generator counting from "1". It is safe for concurrent use, but each generator keeps its own counter and restarts with the process, so the values are unique only within one generator's lifetime - use it in tests, not as a source of durable identifiers.
Example ¶
SequenceGenerator counts from one, which makes it the generator to inject when a test needs to assert on the identifier that was produced.
package main
import (
"fmt"
"github.com/diegodesousas/go-devkit/pkg/gen"
)
func main() {
next := gen.SequenceGenerator()
fmt.Println(next())
fmt.Println(next())
fmt.Println(next())
}
Output: 1 2 3
Example (IndependentCounters) ¶
Each generator keeps its own counter, so two of them do not share a sequence.
package main
import (
"fmt"
"github.com/diegodesousas/go-devkit/pkg/gen"
)
func main() {
first := gen.SequenceGenerator()
second := gen.SequenceGenerator()
fmt.Println(first(), first(), second())
}
Output: 1 2 1
func ULIDGenerator ¶
func ULIDGenerator() StringGenerator
ULIDGenerator returns a generator of ULID strings, which sort lexicographically in creation order.
func UUIDGenerator ¶
func UUIDGenerator() StringGenerator
UUIDGenerator returns a generator of random UUIDv4 strings.
Example ¶
UUIDGenerator produces a random identifier, so only its shape is predictable.
package main
import (
"fmt"
"github.com/diegodesousas/go-devkit/pkg/gen"
)
func main() {
id := gen.UUIDGenerator()()
fmt.Println(len(id))
}
Output: 36