Documentation
¶
Overview ¶
Package uuid generates and parses RFC 9562 UUIDs with the standard library only: random version 4 and time-ordered version 7, both from crypto/rand.
id := uuid.NewV7() // public order ids: sortable, unguessable
u, err := uuid.Parse(r.PathValue("id"))
UUID is a [16]byte that marshals as its canonical text form in JSON (encoding.TextMarshaler) and in SQL (driver.Valuer, sql.Scanner), so it works as a struct field for orm models, request bodies and responses.
See https://github.com/AlexGalhardo/vukem/blob/main/docs/database.md#uuids.
Example ¶
package main
import (
"context"
"fmt"
"github.com/AlexGalhardo/vukem/database"
"github.com/AlexGalhardo/vukem/orm"
"github.com/AlexGalhardo/vukem/uuid"
)
type Order struct {
orm.Model
PublicID uuid.UUID
Parent *uuid.UUID
}
func main() {
ctx := context.Background()
db, _ := database.Open(ctx, ":memory:")
defer db.Close()
_, _ = db.ExecContext(ctx, `CREATE TABLE orders (id INTEGER PRIMARY KEY AUTOINCREMENT,
created_at TIMESTAMP, updated_at TIMESTAMP, public_id TEXT UNIQUE, parent TEXT)`)
o := Order{PublicID: uuid.NewV7()}
if err := orm.Create(ctx, db, &o); err != nil {
fmt.Println(err)
return
}
got, err := orm.QueryOf[Order](db).Where("public_id", o.PublicID).First(ctx)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(got.PublicID == o.PublicID, got.PublicID.Version(), got.Parent == nil)
_, err = uuid.Parse("not-a-uuid")
fmt.Println(err)
}
Output: true 7 true uuid: invalid UUID
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ErrInvalid = errors.New("uuid: invalid UUID")
ErrInvalid reports text that is not a UUID in canonical form.
Functions ¶
This section is empty.
Types ¶
type UUID ¶
type UUID [16]byte
UUID is a 128-bit universally unique identifier. The zero value is the nil UUID (all zeros).
func NewV7 ¶
func NewV7() UUID
NewV7 returns a time-ordered (version 7) UUID: a 48-bit Unix timestamp in milliseconds followed by 74 bits from crypto/rand. UUIDs made in different milliseconds sort by creation time (as bytes and as strings), which keeps B-tree indexes compact; inside one millisecond the order is random. The timestamp is visible to anyone holding the UUID.
func Parse ¶
Parse parses the canonical 36-character form (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx), in either case. Other forms (braces, urn:uuid:, no hyphens) are rejected. It does not check the version: use Version for that.
func (UUID) MarshalText ¶
MarshalText implements encoding.TextMarshaler (JSON strings, query strings).
func (*UUID) Scan ¶
Scan implements sql.Scanner for text (string or []byte) and 16-byte binary columns. NULL is an error: scan nullable columns into a *UUID.
func (UUID) Time ¶
Time returns the creation time of a version 7 UUID (millisecond precision, UTC); ok is false for other versions.
func (*UUID) UnmarshalText ¶
UnmarshalText implements encoding.TextUnmarshaler with Parse's rules; an empty string is an error, not the nil UUID.