unixid

package module
v0.0.58 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 16, 2025 License: MIT Imports: 7 Imported by: 6

README

UnixID

A Go library for generating unique, time-based IDs using Unix timestamps at nanosecond precision.

Overview

UnixID provides functionality for generating and managing unique identifiers with the following features:

  • High-performance ID generation based on Unix nanosecond timestamps
  • Thread-safe concurrent ID generation
  • Built-in collision avoidance through sequential numbering
  • Support for both server-side and client-side (WebAssembly) environments
  • Date conversion utilities for timestamp-to-date formatting

Installation

go get github.com/cdvelop/unixid

Quick Start

Server-side Usage
package main

import (
	"fmt"
	"github.com/cdvelop/unixid"
)

func main() {
	// Create a new UnixID handler (server-side)
	idHandler, err := unixid.NewHandler()
	if err != nil {
		panic(err)
	}

	// Generate a new unique ID
	id, err := idHandler.GetNewID()
	if err != nil {
		panic(err)
	}

	fmt.Printf("Generated ID: %s\n", id)
	// Output: Generated ID: 1624397134562544800

	// Convert an ID to a human-readable date
	dateStr, err := idHandler.UnixNanoToStringDate(id)
	if err != nil {
		panic(err)
	}

	fmt.Printf("ID timestamp represents: %s\n", dateStr)
	// Output: ID timestamp represents: 2021-06-23 15:38:54
}
Client-side (WebAssembly) Usage

For WebAssembly environments, you need to provide a session number handler:

// Example session handler implementation
type sessionHandler struct{}

func (sessionHandler) userSessionNumber() (number string, err error) {
	// In a real application, this would return the user's session number
	return "42", nil
}

// Create a new UnixID handler with session handler
idHandler, err := unixid.NewHandler(&sessionHandler{})

ID Format

The generated IDs follow this format:

  • Server-side: [unix_timestamp_in_nanoseconds] (e.g., 1624397134562544800)
  • Client-side: [unix_timestamp_in_nanoseconds].[user_session_number] (e.g., 1624397134562544800.42)

API Reference

Core Functions
  • NewHandler(...): Creates a new UnixID handler for ID generation
  • GetNewID(): Generates a new unique ID
  • UnixNanoToStringDate(unixNanoStr): Converts a Unix nanosecond timestamp ID to a human-readable date
Additional Utility Functions
  • UnixSecondsToTime(unixSeconds int64) string: Converts a Unix timestamp in seconds to a formatted time string (HH:mm:ss). e.g., 1624397134 -> 15:38:54

Validate ID

The ValidateID function validates and parses a given ID string. It returns the parsed ID as an int64 and an error if the ID is invalid.

Example
package main

import (
	"fmt"
	"github.com/cdvelop/unixid"
)

func main() {
	id := "1624397134562544800"
	parsedID, err := unixid.ValidateID(id)
	if err != nil {
		panic(err)
	}

	fmt.Printf("Parsed ID: %d\n", parsedID)
	// Output: Parsed ID: 1624397134562544800
}

Thread Safety

The library handles concurrent ID generation safely through mutex locking in server-side environments.

License

See the LICENSE file for details.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ValidateID added in v0.0.57

func ValidateID(new_id_in string) (id int64, err error)

ValidateID validates and parses a Unix timestamp ID string. It handles IDs in both server format (just timestamp) and client format (timestamp.userNumber). This function extracts the timestamp portion from the ID and returns it as an int64.

Parameters:

  • new_id_in: The ID string to validate (e.g., "1624397134562544800" or "1624397134562544800.42")

Returns:

  • id: The timestamp portion of the ID as an int64 value
  • err: An error if the ID format is invalid

Validation rules:

  • The ID must contain only digits and at most one decimal point
  • The timestamp portion (before the decimal point) must be a valid int64

Types

type Config added in v0.0.54

type Config struct {
	// Session provides user session numbers in WebAssembly environments
	Session userSessionNumber // e.g., userSessionNumber() string = "1","4","4000" etc.
	// contains filtered or unexported fields
}

Config holds the configuration and dependencies for a UnixID instance

type UnixID

type UnixID struct {

	// Config holds the external dependencies for the UnixID
	*Config
	// contains filtered or unexported fields
}

UnixID is the main struct for ID generation and handling It contains all configuration and state needed for ID generation

func NewHandler

func NewHandler(none ...any) (*UnixID, error)

NewHandler creates a new UnixID handler for server-side environments. This version doesn't require a session handler as user numbers aren't needed in server environments. Returns an initialized UnixID instance ready to generate unique IDs.

func (*UnixID) FieldType added in v0.0.55

func (u *UnixID) FieldType(tableName, fieldName string) (ID, PK bool)

FieldType determines if a field is an ID field and/or a primary key field. This function analyzes field names to identify ID fields and primary keys based on naming conventions.

Parameters:

  • tableName: The name of the table or entity that the field belongs to
  • fieldName: The name of the field to analyze

Returns:

  • ID: true if the field is an ID field (starts with "id")
  • PK: true if the field is a primary key (is named "id" or matches the pattern "id{tableName}" or "id_{tableName}")

Examples:

  • FieldType("user", "id") returns (true, true)
  • FieldType("user", "iduser") returns (true, true)
  • FieldType("user", "id_user") returns (true, true)
  • FieldType("user", "idaddress") returns (true, false)

func (*UnixID) GetNewID

func (id *UnixID) GetNewID() (string, error)

GetNewID generates a new unique ID based on Unix nanosecond timestamp. In server environments, this returns just the Unix nanosecond timestamp value. The method is thread-safe and handles concurrent access through a mutex lock. Returns a string representation of the unique ID.

func (*UnixID) SetValue added in v0.0.55

func (id *UnixID) SetValue(rv *reflect.Value, valueOut *string, sizeOut []byte) error

SetValue sets a unique ID value to a struct field using reflection. This is used internally to populate struct fields with unique IDs. Parameters:

  • rv: A reflect.Value pointer to the struct field that will receive the ID
  • valueOut: A pointer to a string that will store the generated ID
  • sizeOut: A byte slice that will track the size of the generated value

Returns nil on success or an error if the operation fails.

func (*UnixID) UnixNanoToStringDate added in v0.0.54

func (u *UnixID) UnixNanoToStringDate(unixNanoStr string) (string, error)

UnixNanoToStringDate converts a Unix nanosecond timestamp ID to a human-readable date string. This function accepts a string representation of a Unix nanosecond timestamp (with or without a user number suffix) and returns a formatted date string in the format "2006-01-02 15:04" (year-month-day hour:minute).

Parameters:

  • unixNanoStr: String representation of a Unix timestamp in nanoseconds (e.g. "1624397134562544800" or "1624397134562544800.42")

Returns:

  • A formatted date string (e.g. "2021-06-22 15:32")
  • An error if the input is invalid or the conversion fails

Example:

dateStr, err := handler.UnixNanoToStringDate("1624397134562544800")
if err != nil {
  // handle error
}
fmt.Println(dateStr) // e.g. "2021-06-22 15:32"

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL