Documentation
¶
Index ¶
- func ValidateID(new_id_in string) (id int64, err error)
- type Config
- type UnixID
- func (u *UnixID) FieldType(tableName, fieldName string) (ID, PK bool)
- func (id *UnixID) GetNewID() string
- func (id *UnixID) SetNewID(target any)
- func (u *UnixID) UnixNanoToStringDate(unixNanoStr string) (string, error)
- func (id *UnixID) UnixNanoToTime(input any) string
- func (id *UnixID) UnixSecondsToDate(unixSeconds int64) string
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func ValidateID ¶ added in v0.0.57
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. // TimeProvider provides time utilities including nanosecond timestamps and date formatting TimeProvider tinytime.TimeProvider // Provides UnixNano(), UnixSecondsToDate(), and UnixNanoToTime() // 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 NewUnixID ¶ added in v0.0.59
NewUnixID creates a new UnixID handler with appropriate configuration based on the runtime environment.
For WebAssembly environments (client-side): - Requires a userSessionNumber handler to be passed as a parameter - Creates IDs with format: "[timestamp].[user_number]" (e.g., "1624397134562544800.42") - No mutex is used as JavaScript is single-threaded
For non-WebAssembly environments (server-side): - Does not require any parameters - Creates IDs with format: "[timestamp]" (e.g., "1624397134562544800") - Uses a sync.Mutex for thread safety
IMPORTANT: When integrating with other libraries that also use sync.Mutex, you can pass an existing mutex as a parameter to avoid potential deadlocks. When an external mutex is provided, this library will use a no-op mutex internally to prevent deadlocks when GetNewID is called within a context that has already acquired the same mutex. This assumes that external synchronization is being handled by the caller.
Parameters:
- handlerUserSessionNumber: Optional userSessionNumber implementation (required for WebAssembly)
- sync.Mutex or *sync.Mutex: Optional mutex to use instead of creating a new one (server-side only)
Returns:
- A configured *UnixID instance
- An error if the configuration is invalid
Usage examples:
// Server-side usage: idHandler, err := unixid.NewUnixID() // WebAssembly usage: type sessionHandler struct{} func (sessionHandler) userSessionNumber() string { return "42" } idHandler, err := unixid.NewUnixID(&sessionHandler{}) // Server-side usage with existing mutex to avoid deadlocks: var mu sync.Mutex idHandler, err := unixid.NewUnixID(&mu) // With external mutex, when calling within a locked context: var mu sync.Mutex idHandler, err := unixid.NewUnixID(&mu) mu.Lock() defer mu.Unlock() // This won't deadlock because NewUnixID uses a no-op mutex internally // when an external mutex is provided id := idHandler.GetNewID()
func (*UnixID) FieldType ¶ added in v0.0.55
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 ¶
GetNewID generates a new unique ID based on Unix nanosecond timestamp. In WebAssembly environments, this appends a user session number to the timestamp. In server environments, this returns just the Unix nanosecond timestamp. Returns a string representation of the unique ID.
func (*UnixID) SetNewID ¶ added in v0.0.62
SetNewID sets a new unique ID value to various types of targets. It generates a new unique ID based on Unix nanosecond timestamp and assigns it to the provided target. This function can work with multiple target types including tinyreflect.Value, string pointers, and byte slices.
In WebAssembly environments, IDs include a user session number as a suffix (e.g., "1624397134562544800.42"). In server environments, IDs are just the timestamp (e.g., "1624397134562544800").
Parameters:
- target: The target to receive the new ID. Can be:
- tinyreflect.Value or *tinyreflect.Value: For setting struct field values via tiny-reflection.
- *string: For setting a string variable directly.
- []byte: For appending the ID to a byte slice.
This function is thread-safe in server-side environments.
Examples:
// Setting a struct field using tiny-reflection v := tinyreflect.ValueOf(&myStruct) elem, _ := v.Elem() field, _ := elem.Field(0) // Get field by index idHandler.SetNewID(field) // Setting a string variable var id string idHandler.SetNewID(&id) // Appending to a byte slice buf := make([]byte, 0, 64) idHandler.SetNewID(buf)
func (*UnixID) UnixNanoToStringDate ¶ added in v0.0.54
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"
func (*UnixID) UnixNanoToTime ¶ added in v0.0.68
UnixNanoToTime converts a Unix timestamp in nanoseconds to a formatted time string. Format: "15:04:05" (hour:minute:second) It accepts a parameter of type any and attempts to convert it to an int64 Unix timestamp in nanoseconds. eg: 1624397134562544800 -> "15:32:14" supported types: int64, int, float64, string
func (*UnixID) UnixSecondsToDate ¶ added in v0.0.93
UnixSecondsToDate converts Unix seconds to a formatted date string. Format: "2006-01-02 15:04" (YYYY-MM-DD HH:MM) eg: 1624397134 -> "2021-06-22 15:32"