https://github.com/trilliot/safeid
Go type-safe identifiers made easy
https://github.com/trilliot/safeid
go golang human-readable id identifier type-safe uuid uuidv7
Last synced: 4 months ago
JSON representation
Go type-safe identifiers made easy
- Host: GitHub
- URL: https://github.com/trilliot/safeid
- Owner: trilliot
- License: mit
- Created: 2024-11-21T22:25:57.000Z (7 months ago)
- Default Branch: main
- Last Pushed: 2024-11-28T17:43:16.000Z (7 months ago)
- Last Synced: 2025-01-23T07:11:23.239Z (5 months ago)
- Topics: go, golang, human-readable, id, identifier, type-safe, uuid, uuidv7
- Language: Go
- Homepage:
- Size: 23.4 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# SafeID
#### A human-readable, K-sortable, type-safe at compile-time, UUIDv7-backed globally unique identifiers for Go.
[](https://opensource.org/licenses/MIT)
When dealing with commonly accepted unique identifiers such as UUIDs,
it is hard to know what they represent at first glance.SafeIDs are designed to be:
- **human readable:** SafeIDs are prefixed by a _type_, followed by a 22 characters string (e.g.: `user_02Yjy1AYf1ckS6jBZ5zw3G`)
- **K-sortable:** based on the UUIDv7 specification, both UUID or String representation of a SafeID are K-sortable
- **type-safe:** it is not possible to parse one SafeID type into another when dealing with their string representation
- **compile-time safe:** thanks to generics, your code will not compile if you try to pass one SafeID type into another
- **database efficient:** when stored into a database, SafeID can leverage `uuid` column types## Installation
```
go get github.com/trilliot/safeid
```## Usage
You can create either generic (`safeid.Generic`) or custom typed SafeID:
```go
// Create a generic type without prefix (not recommended)
id, err := safeid.New[safeid.Generic]()// Or create a custom type that satisfies the safeid.Prefixer interface
type User struct {}
func (User) Prefix() string { return "user" }id, err := safeid.New[User]()
```An SafeID can be retrieved in its String or UUID form:
```go
id.String() // user_02Yjy1AYf1ckS6jBZ5zw3G
id.UUID() // 0193508b-e85e-7812-ba4b-91d85495d7bc
```When dealing with JSON, the type-safe form is (un)marshaled:
```go
obj := map[string]any{
"id": safeid.Must(safeid.New[User]()),
}
json.Marshal(obj, ...) // {"id": "user_02Yjy1AYf1ckS6jBZ5zw3G"}
```When passed to or scanned from PostgreSQL, the UUID form is used:
```go
var id safeid.ID[User]
rows.Scan(&id) // 0193508b-e85e-7812-ba4b-91d85495d7bc
```