Documentation ¶
Overview ¶
Package gonuts provides enhanced error handling functionality with structured error messages, error codes, context, stack trace support, and logging integration.
Index ¶
- Constants
- Variables
- func ApplyDefaults(config *MarkdownGeneratorConfig) error
- func AssignToCastBoolOr(val any, fallbackVal bool) bool
- func AssignToCastInt64Or(val any, fallbackVal int64) int64
- func AssignToCastStringOr(val any, fallbackVal string) string
- func BoolPtr(b bool) *bool
- func BytesToGB(size int64, digits int) (terrabytes float64)
- func BytesToKB(size int64, digits int) (kilobytes float64)
- func BytesToMB(size int64, digits int) (megabytes float64)
- func BytesToNiceString(size int64) (formattedString string)
- func BytesToTB(size int64, digits int) (terrabytes float64)
- func Chunk[T any](slice []T, chunkSize int) [][]T
- func ComparePasswords(hashedPwd string, inputPwd string) bool
- func ConcurrentMapReduce[T, R any](ctx context.Context, input []T, mapFunc MapFunc[T, R], ...) (R, error)
- func Contains[T comparable](slice []T, element T) bool
- func Debounce(fn any, duration time.Duration, callback func(int)) func(...any)
- func Filter[T any](slice []T, predicate func(T) bool) []T
- func Float32Ptr(f float32) *float32
- func Float64Ptr(f float64) *float64
- func ForceUpdateVersionData() error
- func GenerateMarkdownFromFiles(config *MarkdownGeneratorConfig) error
- func GeneratePassword(p string) string
- func GenerateRandomString(chars []rune, length int) string
- func GetGitBranch() string
- func GetGitCommit() string
- func GetPrettyJson(object any) (pretty string)
- func GetVersion() string
- func IfThen(condition Condition, action Action)
- func IfThenElse(condition Condition, thenAction, elseAction Action)
- func IndexOf[T comparable](slice []T, element T) int
- func InitVersion()
- func Init_Logger(targetLevel zapcore.Level, instanceId string, log2file bool, ...) *zap.SugaredLogger
- func Int32Ptr(i int32) *int32
- func Int64Ptr(i int64) *int64
- func IntPtr(i int) *int
- func IsNID(id string, prefix string, length int) bool
- func Join(slice []string, separator string) string
- func Map[T, R any](slice []T, f func(T) R) []R
- func NID(prefix string, length int) string
- func NanoID(prefix string) string
- func NormalizePassword(p string) []byte
- func ParallelSliceMap[T, R any](ctx context.Context, input []T, mapFunc MapFunc[T, R]) ([]R, error)
- func PrintMemoryUsage() bool
- func Ptr[T any](v T) *T
- func Reduce[T, R any](slice []T, initial R, reducer func(R, T) R) R
- func Remove[T comparable](slice []T, element T) []T
- func RemoveAt[T any](slice []T, index int) []T
- func RemoveJsonFields(obj any, fieldsToRemove []string) (string, error)
- func Retry(ctx context.Context, attempts int, initialDelay, maxDelay time.Duration, ...) error
- func Reverse[T any](slice []T) []T
- func Round(val float64, roundOn float64, places int) (newVal float64)
- func SafeSQLString(s string) string
- func SanitizeString(badStringsList []string, stringToClean string) string
- func SelectJsonFields(obj any, fieldsToSelect []string) (string, error)
- func SetErrorLogger(logger *zap.SugaredLogger)
- func SetLoglevel(loglevel string, instanceId string, log2file bool, logfilePath string)
- func Sort[T any](slice []T, less func(T, T) bool)
- func StrPtr(s string) *string
- func StringSliceContains(s []string, e string) bool
- func StringSliceIndexOf(s []string, e string) int
- func StringSliceRemoveIndex(s []string, index int) []string
- func StringSliceRemoveString(max int, sourceSlice []string, stringToRemove string) []string
- func StringSlicesHaveSameContent(source []string, compare []string) bool
- func SyslogTimeEncoder(t time.Time, enc zapcore.PrimitiveArrayEncoder)
- func TimeFromJSTimestamp(timestamp int64) time.Time
- func TimeFromUnixTimestamp(timestamp int64) time.Time
- func TimeToJSTimestamp(t time.Time) int64
- func Uint32Ptr(u uint32) *uint32
- func Uint64Ptr(u uint64) *uint64
- func Unique[T comparable](slice []T) []T
- type Action
- type CircuitBreaker
- type CircuitBreakerState
- type CommandLineParameters
- type ConcurrentMap
- func (cm *ConcurrentMap[K, V]) Clear()
- func (cm *ConcurrentMap[K, V]) Delete(key K)
- func (cm *ConcurrentMap[K, V]) Get(key K) (V, bool)
- func (cm *ConcurrentMap[K, V]) GetOrSet(key K, value V) (V, bool)
- func (cm *ConcurrentMap[K, V]) Keys() []K
- func (cm *ConcurrentMap[K, V]) Len() int
- func (cm *ConcurrentMap[K, V]) Range(f func(K, V) bool)
- func (cm *ConcurrentMap[K, V]) Set(key K, value V)
- func (cm *ConcurrentMap[K, V]) SetIfAbsent(key K, value V) bool
- func (cm *ConcurrentMap[K, V]) Values() []V
- type Condition
- type ConditionalExecution
- func (ce *ConditionalExecution) Else(action Action) *ConditionalExecution
- func (ce *ConditionalExecution) ElseIf(condition Condition) *ConditionalExecution
- func (ce *ConditionalExecution) Execute()
- func (ce *ConditionalExecution) ExecuteWithFallthrough()
- func (ce *ConditionalExecution) If(condition Condition) *ConditionalExecution
- func (ce *ConditionalExecution) Then(action Action) *ConditionalExecution
- type ErrorPlus
- func (e *ErrorPlus) As(target interface{}) bool
- func (e *ErrorPlus) Code() int
- func (e *ErrorPlus) CodeStr() string
- func (e *ErrorPlus) Context() map[string]interface{}
- func (e *ErrorPlus) ContextStr() string
- func (e *ErrorPlus) Error() string
- func (e *ErrorPlus) Format(f fmt.State, c rune)
- func (e *ErrorPlus) Is(target error) bool
- func (e *ErrorPlus) Log()
- func (e *ErrorPlus) MarshalJSON() ([]byte, error)
- func (e *ErrorPlus) Msg() string
- func (e *ErrorPlus) StackTrace() []string
- func (e *ErrorPlus) Timestamp() time.Time
- func (e *ErrorPlus) Unwrap() error
- func (e *ErrorPlus) WithCode(code int) *ErrorPlus
- func (e *ErrorPlus) WithContext(key string, value interface{}) *ErrorPlus
- func (e *ErrorPlus) WithMsg(msg string) *ErrorPlus
- func (e *ErrorPlus) WithValues(msg string, code int) *ErrorPlus
- type EventData
- type EventEmitter
- func (ee *EventEmitter) Emit(event string, args ...interface{}) error
- func (ee *EventEmitter) EmitConcurrent(event string, args ...interface{}) error
- func (ee *EventEmitter) Events() []string
- func (ee *EventEmitter) ListenerCount(event string) int
- func (ee *EventEmitter) ListenerNames(event string) []string
- func (ee *EventEmitter) Off(event, name string) error
- func (ee *EventEmitter) On(event, name string, fn interface{}) (string, error)
- func (ee *EventEmitter) Once(event, name string, fn interface{}) (string, error)
- type EventID
- type GoInterval
- type JSONPathExtractor
- func (jpe *JSONPathExtractor) Extract(path string) (interface{}, error)
- func (jpe *JSONPathExtractor) ExtractArray(path string) ([]interface{}, error)
- func (jpe *JSONPathExtractor) ExtractBool(path string) (bool, error)
- func (jpe *JSONPathExtractor) ExtractFloat(path string) (float64, error)
- func (jpe *JSONPathExtractor) ExtractInt(path string) (int, error)
- func (jpe *JSONPathExtractor) ExtractMultiple(paths ...string) (map[string]interface{}, error)
- func (jpe *JSONPathExtractor) ExtractString(path string) (string, error)
- type MapFunc
- type MarkdownGeneratorConfig
- type MemoizedFunc
- type PaginationInfo
- type RateLimiter
- type ReduceFunc
- type SMAction
- type SMCondition
- type Set
- func (s *Set[T]) Add(items ...T) *Set[T]
- func (s *Set[T]) Clear()
- func (s *Set[T]) Contains(item T) bool
- func (s *Set[T]) Difference(other *Set[T]) *Set[T]
- func (s *Set[T]) Intersection(other *Set[T]) *Set[T]
- func (s *Set[T]) Remove(items ...T) *Set[T]
- func (s *Set[T]) Size() int
- func (s *Set[T]) String() string
- func (s *Set[T]) ToSlice() []T
- func (s *Set[T]) Union(other *Set[T]) *Set[T]
- type State
- type StateID
- type StatesMan
- func (sm *StatesMan) AddPostHook(hook SMAction)
- func (sm *StatesMan) AddPreHook(hook SMAction)
- func (sm *StatesMan) AddState(id StateID, name string, entryActions, exitActions []SMAction)
- func (sm *StatesMan) AddTimedTransition(from, to StateID, duration time.Duration, actions ...SMAction)
- func (sm *StatesMan) AddTransition(from, to StateID, event EventID, condition SMCondition, actions ...SMAction)
- func (sm *StatesMan) Export() (string, error)
- func (sm *StatesMan) GenerateDOT() string
- func (sm *StatesMan) GetCurrentState() StateID
- func (sm *StatesMan) Import(jsonStr string) error
- func (sm *StatesMan) Run()
- func (sm *StatesMan) SetInitialState(id StateID) error
- func (sm *StatesMan) TriggerEvent(event EventID, data map[string]interface{})
- type TimedTransition
- type Transition
- type Trie
- func (t *Trie) AutoComplete(prefix string, limit int) []string
- func (t *Trie) BulkInsert(words []string)
- func (t *Trie) Insert(word string)
- func (t *Trie) InsertWithValue(word string, value interface{})
- func (t *Trie) LongestCommonPrefix() string
- func (t *Trie) Search(word string) bool
- func (t *Trie) StartsWith(prefix string) bool
- func (t *Trie) WildcardSearch(pattern string) []string
- type TrieNode
- type URLBuilder
- func (b *URLBuilder) AddPath(segment string) *URLBuilder
- func (b *URLBuilder) AddQuery(key, value string) *URLBuilder
- func (b *URLBuilder) Build() string
- func (b *URLBuilder) BuildURL() (*url.URL, error)
- func (b *URLBuilder) Clone() *URLBuilder
- func (b *URLBuilder) RemoveQuery(key string) *URLBuilder
- func (b *URLBuilder) SetCredentials(username, password string) *URLBuilder
- func (b *URLBuilder) SetFragment(fragment string) *URLBuilder
- func (b *URLBuilder) SetHost(host string) *URLBuilder
- func (b *URLBuilder) SetPath(path string) *URLBuilder
- func (b *URLBuilder) SetPort(port string) *URLBuilder
- func (b *URLBuilder) SetQuery(key, value string) *URLBuilder
- func (b *URLBuilder) SetScheme(scheme string) *URLBuilder
- type VersionData
Constants ¶
const NID_Prefix_Separator = "_"
Variables ¶
var ( UUIDRegEx = regexp.MustCompile("^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-4[a-fA-F0-9]{3}-[8|9|aA|bB][a-fA-F0-9]{3}-[a-fA-F0-9]{12}$") NotLegalIdCharacters = regexp.MustCompile("[^A-Za-z0-9-_]") ErrBadUUID = errors.New("uuid format error") ErrBadId = errors.New("bad id format") ErrIllegalId = errors.New("illegal id") ErrUnknownId = errors.New("unknown id") ErrMalformedId = errors.New("malformed id") )
var ErrCircuitOpen = errors.New("circuit breaker is open")
ErrCircuitOpen is returned when the circuit breaker is in the open state
var L = Init_Logger(zapcore.DebugLevel, "unknown", false, "logs/")
var SANITIZE_SQLSAFER = []string{"`", "´", "'", " OR ", " or ", "=", ";", ":", "(", ")", "--", "/*", "*/", "@@", "@"}
SANITIZE_SQLSAFER is a list of strings that are commonly used in SQL injection attacks. NOTE: This is not a comprehensive list and should not be relied upon for complete SQL injection protection.
Functions ¶
func ApplyDefaults ¶ added in v0.2.0
func ApplyDefaults(config *MarkdownGeneratorConfig) error
func AssignToCastBoolOr ¶
func AssignToCastInt64Or ¶
func AssignToCastStringOr ¶
func BytesToNiceString ¶
func Chunk ¶ added in v0.2.0
Chunk splits a slice into chunks of a specified size.
Example:
numbers := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} fmt.Println(Chunk(numbers, 3)) // Output: [[1 2 3] [4 5 6] [7 8 9] [10]]
func ComparePasswords ¶
ComparePasswords func for a comparing password.
func ConcurrentMapReduce ¶ added in v0.2.0
func ConcurrentMapReduce[T, R any]( ctx context.Context, input []T, mapFunc MapFunc[T, R], reduceFunc ReduceFunc[R], initialValue R, ) (R, error)
ConcurrentMapReduce performs a map-reduce operation concurrently on the input slice
This function applies the mapFunc to each element of the input slice concurrently, and then reduces the results using the reduceFunc. It utilizes all available CPU cores for maximum performance and uses the existing ConcurrentMap for intermediate results.
Parameters:
- ctx: A context for cancellation
- input: A slice of input values
- mapFunc: A function to apply to each input value
- reduceFunc: A function to combine mapped values
- initialValue: The initial value for the reduction
Returns:
- R: The final reduced result
- error: An error if the operation was cancelled or failed
Example usage:
input := []int{1, 2, 3, 4, 5} result, err := ConcurrentMapReduce( context.Background(), input, func(x int) int { return x * x }, // Map: Square each number func(a, b int) int { return a + b }, // Reduce: Sum the squares 0, // Initial value for sum ) if err != nil { log.Fatalf("MapReduce failed: %v", err) } fmt.Printf("Sum of squares: %d\n", result) // Output: Sum of squares: 55
func Contains ¶ added in v0.2.0
func Contains[T comparable](slice []T, element T) bool
Contains checks if a slice contains a specific element.
Example:
numbers := []int{1, 2, 3, 4, 5} fmt.Println(Contains(numbers, 3)) // Output: true
func Debounce ¶ added in v0.2.0
Debounce that executes first call immediately and last call after delays in calls
func Filter ¶ added in v0.2.0
Filter returns a new slice containing only the elements that satisfy the predicate.
Example:
numbers := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} evens := Filter(numbers, func(n int) bool { return n%2 == 0 }) fmt.Println(evens) // Output: [2 4 6 8 10]
func Float32Ptr ¶ added in v0.2.0
Float32Ptr returns a pointer to the given float32
func Float64Ptr ¶ added in v0.2.0
Float64Ptr returns a pointer to the given float64
func ForceUpdateVersionData ¶ added in v0.3.0
func ForceUpdateVersionData() error
ForceUpdateVersionData re-reads git data and updates the version file
func GenerateMarkdownFromFiles ¶ added in v0.2.0
func GenerateMarkdownFromFiles(config *MarkdownGeneratorConfig) error
GenerateMarkdownFromFiles generates a markdown file containing code snippets from files in a directory.
config := &gonuts.MarkdownGeneratorConfig{ BaseDir: gonuts.Ptr("/path/to/your/project"), Includes: []string{ "**/*.go", "**/*.md", "**/*.yaml", }, Excludes: []string{ "**/vendor/**", "**/test/**", }, Title: gonuts.Ptr("My Custom Project Documentation"), BaseHeaderLevel: gonuts.Ptr(3), }
func GeneratePassword ¶
GeneratePassword func for a making hash & salt with user password.
func GenerateRandomString ¶
GenerateRandomString creates a random string of a given length using the provided character set.
Parameters:
- chars: A slice of runes representing the character set to use.
- length: The desired length of the random string.
Returns:
- A randomly generated string of the specified length.
Example usage:
chars := []rune("abcdefghijklmnopqrstuvwxyz") randomStr := gonuts.GenerateRandomString(chars, 10) fmt.Println(randomStr) // Output: (a random 10-character string using the given alphabet)
func GetGitBranch ¶ added in v0.2.0
func GetGitBranch() string
func GetGitCommit ¶ added in v0.2.0
func GetGitCommit() string
func GetPrettyJson ¶
func GetVersion ¶ added in v0.2.0
func GetVersion() string
func IfThen ¶ added in v0.2.0
IfThen is a convenience function for simple if-then execution
Parameters:
- condition: a function that returns a boolean
- action: a function to be executed if the condition is true
Example usage:
gonuts.IfThen( func() bool { return x > 10 }, func() { fmt.Println("x is greater than 10") }, )
func IfThenElse ¶ added in v0.2.0
IfThenElse is a convenience function for simple if-then-else execution
Parameters:
- condition: a function that returns a boolean
- thenAction: a function to be executed if the condition is true
- elseAction: a function to be executed if the condition is false
Example usage:
gonuts.IfThenElse( func() bool { return x > 10 }, func() { fmt.Println("x is greater than 10") }, func() { fmt.Println("x is 10 or less") }, )
func IndexOf ¶ added in v0.2.0
func IndexOf[T comparable](slice []T, element T) int
IndexOf returns the index of the first occurrence of an element in a slice, or -1 if not found.
Example:
fruits := []string{"apple", "banana", "cherry"} fmt.Println(IndexOf(fruits, "banana")) // Output: 1
func InitVersion ¶ added in v0.3.0
func InitVersion()
func Init_Logger ¶
func IsNID ¶ added in v0.3.0
IsNID checks if the given ID is a valid NID with the specified prefix and length.
func Join ¶ added in v0.2.0
Join concatenates the elements of a string slice, separated by the specified separator.
Example:
words := []string{"Hello", "World", "Golang"} fmt.Println(Join(words, ", ")) // Output: Hello, World, Golang
func Map ¶ added in v0.2.0
func Map[T, R any](slice []T, f func(T) R) []R
Map applies a function to each element of a slice and returns a new slice.
Example:
numbers := []int{1, 2, 3, 4, 5} squared := Map(numbers, func(n int) int { return n * n }) fmt.Println(squared) // Output: [1 4 9 16 25]
func NID ¶ added in v0.1.1
NID generates a unique ID with a specified length and optional prefix.
It creates a unique identifier of the given length using the idAlphabet. If a prefix is provided, it's prepended to the generated ID.
Parameters:
- prefix: An optional string to be prepended to the generated ID. Use "" for no prefix.
- length: The desired length of the generated part of the ID (excluding prefix).
Returns:
- A string containing the optional prefix followed by a unique identifier of the specified length.
Example usage:
id1 := gonuts.NID("doc", 8) fmt.Println(id1) // Output: doc_r3tM9wK1 id2 := gonuts.NID("", 10) fmt.Println(id2) // Output: 7mHxL2pQ4R
func NanoID ¶
NanoID generates a unique ID with a given prefix.
It uses a cryptographically secure random number generator to create a unique identifier, then prepends the given prefix to it.
Parameters:
- prefix: A string to be prepended to the generated ID.
Returns:
- A string containing the prefix followed by a unique identifier.
Example usage:
id := gonuts.NanoID("user") fmt.Println(id) // Output: user_6ByTSYmGzT2c
func NormalizePassword ¶
NormalizePassword func for a returning the users input as a byte slice.
func ParallelSliceMap ¶ added in v0.2.0
func ParallelSliceMap[T, R any]( ctx context.Context, input []T, mapFunc MapFunc[T, R], ) ([]R, error)
ParallelSliceMap applies a function to each element of a slice concurrently
This function processes a slice in parallel, applying the mapFunc to each element.
Parameters:
- ctx: A context for cancellation
- input: A slice of input values
- mapFunc: A function to apply to each input value
Returns:
- []R: A slice containing the mapped results
- error: An error if the operation was cancelled or failed
Example usage:
input := []string{"hello", "world", "parallel", "map"} result, err := ParallelSliceMap( context.Background(), input, func(s string) int { return len(s) }, // Map: Get length of each string ) if err != nil { log.Fatalf("ParallelSliceMap failed: %v", err) } fmt.Printf("String lengths: %v\n", result) // Output: String lengths: [5 5 8 3]
func PrintMemoryUsage ¶
func PrintMemoryUsage() bool
func Reduce ¶ added in v0.2.0
func Reduce[T, R any](slice []T, initial R, reducer func(R, T) R) R
Reduce applies a reducer function to all elements in a slice, returning a single value.
Example:
numbers := []int{1, 2, 3, 4, 5} sum := Reduce(numbers, 0, func(acc, n int) int { return acc + n }) fmt.Println(sum) // Output: 15
func Remove ¶ added in v0.2.0
func Remove[T comparable](slice []T, element T) []T
Remove removes all occurrences of an element from a slice.
Example:
numbers := []int{1, 2, 3, 2, 4, 2, 5} fmt.Println(Remove(numbers, 2)) // Output: [1 3 4 5]
func RemoveAt ¶ added in v0.2.0
RemoveAt removes the element at a specific index from a slice.
Example:
letters := []string{"a", "b", "c", "d"} fmt.Println(RemoveAt(letters, 2)) // Output: [a b d]
func RemoveJsonFields ¶ added in v0.1.4
from here: https://stackoverflow.com/questions/17306358/removing-fields-from-struct-or-hiding-them-in-json-response by https://stackoverflow.com/users/7496198/chhaileng
func Retry ¶ added in v0.2.0
func Retry(ctx context.Context, attempts int, initialDelay, maxDelay time.Duration, f func() error) error
Retry attempts to execute the given function with exponential backoff.
Parameters:
- ctx: A context.Context for cancellation.
- attempts: The maximum number of retry attempts.
- initialDelay: The initial delay between retries.
- maxDelay: The maximum delay between retries.
- f: The function to be executed.
Returns:
- error: nil if the function succeeds, otherwise the last error encountered.
The function uses exponential backoff with jitter to space out retry attempts. It will stop retrying if the context is cancelled or the maximum number of attempts is reached.
Example usage:
err := gonuts.Retry(ctx, 5, time.Second, time.Minute, func() error { return someUnreliableOperation() }) if err != nil { log.Printf("Operation failed after retries: %v", err) }
func Reverse ¶ added in v0.2.0
func Reverse[T any](slice []T) []T
Reverse returns a new slice with elements in reverse order.
Example:
numbers := []int{1, 2, 3, 4, 5} fmt.Println(Reverse(numbers)) // Output: [5 4 3 2 1]
func SafeSQLString ¶ added in v0.2.0
SafeSQLString prepares a string for safe use in SQL queries by escaping single quotes.
WARNING: This function should be used in conjunction with parameterized queries, not as a replacement for them. It does not provide complete protection against SQL injection.
Parameters:
- s: The input string to be escaped.
Returns:
- An escaped version of the input string, safe for use in SQL queries.
Example usage:
userInput := "O'Reilly" safeName := gonuts.SafeSQLString(userInput) query := fmt.Sprintf("SELECT * FROM authors WHERE name = '%s'", safeName) // Use parameterized queries instead of string formatting in production code
func SanitizeString ¶ added in v0.1.2
SanitizeString removes potentially dangerous strings from the input.
WARNING: This function provides basic sanitization and should not be considered a complete solution for preventing SQL injection or other security vulnerabilities. Always use parameterized queries and proper input validation in addition to this function.
Parameters:
- badStringsList: A slice of strings to be removed from the input.
- stringToClean: The input string to be sanitized.
Returns:
- A sanitized version of the input string.
Example usage:
input := "SELECT * FROM users WHERE name = 'John' OR 1=1; --" sanitized := gonuts.SanitizeString(gonuts.SANITIZE_SQLSAFER, input) fmt.Println(sanitized) // Output: SELECT * FROM users WHERE name John
func SelectJsonFields ¶ added in v0.1.4
func SetErrorLogger ¶ added in v0.3.1
func SetErrorLogger(logger *zap.SugaredLogger)
SetErrorLogger allows injecting a custom logger for ErrorPlus instances.
func SetLoglevel ¶
func Sort ¶ added in v0.2.0
Sort sorts a slice in ascending order (requires a less function).
Example:
numbers := []int{3, 1, 4, 1, 5, 9, 2, 6} Sort(numbers, func(a, b int) bool { return a < b }) fmt.Println(numbers) // Output: [1 1 2 3 4 5 6 9]
func StringSliceContains ¶
@Summary StringSliceContains checks if a string slice contains a string.
func StringSliceIndexOf ¶
func StringSliceRemoveIndex ¶
func StringSliceRemoveString ¶
func SyslogTimeEncoder ¶
func SyslogTimeEncoder(t time.Time, enc zapcore.PrimitiveArrayEncoder)
func TimeFromJSTimestamp ¶ added in v0.1.4
this is just to remember that javascript Date.now() converts like this
func TimeFromUnixTimestamp ¶
func TimeToJSTimestamp ¶ added in v0.1.4
this is just to remember that javascript Date.now() converts like this
func Unique ¶ added in v0.2.0
func Unique[T comparable](slice []T) []T
Unique returns a new slice with duplicate elements removed.
Example:
numbers := []int{1, 2, 2, 3, 3, 3, 4, 5, 5} fmt.Println(Unique(numbers)) // Output: [1 2 3 4 5]
Types ¶
type Action ¶ added in v0.2.0
type Action func()
Action represents a function that performs some action
type CircuitBreaker ¶ added in v0.2.0
type CircuitBreaker struct {
// contains filtered or unexported fields
}
CircuitBreaker implements the Circuit Breaker pattern
func NewCircuitBreaker ¶ added in v0.2.0
func NewCircuitBreaker(failureThreshold uint, resetTimeout time.Duration, halfOpenSuccess uint) *CircuitBreaker
NewCircuitBreaker creates a new CircuitBreaker
Parameters:
- failureThreshold: number of failures before opening the circuit
- resetTimeout: duration to wait before attempting to close the circuit
- halfOpenSuccess: number of successes in half-open state to close the circuit
Returns:
- *CircuitBreaker: a new instance of CircuitBreaker
Example usage:
cb := gonuts.NewCircuitBreaker(5, 10*time.Second, 2) err := cb.Execute(func() error { return someRiskyOperation() }) if err != nil { if errors.Is(err, gonuts.ErrCircuitOpen) { log.Println("Circuit is open, not attempting operation") } else { log.Printf("Operation failed: %v", err) } }
func (*CircuitBreaker) Execute ¶ added in v0.2.0
func (cb *CircuitBreaker) Execute(f func() error) error
Execute runs the given function if the circuit is closed or half-open
Parameters:
- f: the function to execute
Returns:
- error: nil if the function succeeds, ErrCircuitOpen if the circuit is open, or the error returned by the function
func (*CircuitBreaker) LastError ¶ added in v0.2.0
func (cb *CircuitBreaker) LastError() error
LastError returns the last error that occurred
func (*CircuitBreaker) State ¶ added in v0.2.0
func (cb *CircuitBreaker) State() CircuitBreakerState
State returns the current state of the circuit breaker
type CircuitBreakerState ¶ added in v0.2.0
type CircuitBreakerState int
CircuitBreakerState represents the current state of the circuit breaker
const ( StateClosed CircuitBreakerState = iota StateOpen StateHalfOpen )
type CommandLineParameters ¶
type ConcurrentMap ¶ added in v0.2.0
type ConcurrentMap[K comparable, V any] struct { // contains filtered or unexported fields }
ConcurrentMap is a thread-safe map implementation
func NewConcurrentMap ¶ added in v0.2.0
func NewConcurrentMap[K comparable, V any](numShards int) *ConcurrentMap[K, V]
NewConcurrentMap creates a new ConcurrentMap with the specified number of shards.
Example:
cm := NewConcurrentMap[string, int](16)
func (*ConcurrentMap[K, V]) Clear ¶ added in v0.2.0
func (cm *ConcurrentMap[K, V]) Clear()
Clear removes all items from the map.
Example:
cm.Clear()
func (*ConcurrentMap[K, V]) Delete ¶ added in v0.2.0
func (cm *ConcurrentMap[K, V]) Delete(key K)
Delete removes a key-value pair from the map.
Example:
cm.Delete("key")
func (*ConcurrentMap[K, V]) Get ¶ added in v0.2.0
func (cm *ConcurrentMap[K, V]) Get(key K) (V, bool)
Get retrieves a value from the map.
Example:
value, exists := cm.Get("key") if exists { fmt.Println(value) }
func (*ConcurrentMap[K, V]) GetOrSet ¶ added in v0.2.0
func (cm *ConcurrentMap[K, V]) GetOrSet(key K, value V) (V, bool)
GetOrSet returns the existing value for the key if present. Otherwise, it sets and returns the given value.
Example:
value, loaded := cm.GetOrSet("key", 42) if loaded { fmt.Println("Key already existed") } else { fmt.Println("New key-value pair added") }
func (*ConcurrentMap[K, V]) Keys ¶ added in v0.2.0
func (cm *ConcurrentMap[K, V]) Keys() []K
Keys returns a slice of all keys in the map.
Example:
keys := cm.Keys() for _, key := range keys { fmt.Println(key) }
func (*ConcurrentMap[K, V]) Len ¶ added in v0.2.0
func (cm *ConcurrentMap[K, V]) Len() int
Len returns the total number of items in the map.
Example:
count := cm.Len() fmt.Printf("Map contains %d items\n", count)
func (*ConcurrentMap[K, V]) Range ¶ added in v0.2.0
func (cm *ConcurrentMap[K, V]) Range(f func(K, V) bool)
Range calls the given function for each key-value pair in the map.
Example:
cm.Range(func(key string, value int) bool { fmt.Printf("Key: %s, Value: %d\n", key, value) return true // continue iteration })
func (*ConcurrentMap[K, V]) Set ¶ added in v0.2.0
func (cm *ConcurrentMap[K, V]) Set(key K, value V)
Set adds a key-value pair to the map or updates the value if the key already exists.
Example:
cm.Set("key", 42)
func (*ConcurrentMap[K, V]) SetIfAbsent ¶ added in v0.2.0
func (cm *ConcurrentMap[K, V]) SetIfAbsent(key K, value V) bool
SetIfAbsent sets the value for a key only if it is not already present.
Example:
added := cm.SetIfAbsent("key", 42) if added { fmt.Println("Value was set") } else { fmt.Println("Key already existed") }
func (*ConcurrentMap[K, V]) Values ¶ added in v0.2.0
func (cm *ConcurrentMap[K, V]) Values() []V
Values returns a slice of all values in the map.
Example:
values := cm.Values() for _, value := range values { fmt.Println(value) }
type Condition ¶ added in v0.2.0
type Condition func() bool
Condition represents a function that returns a boolean
type ConditionalExecution ¶ added in v0.2.0
type ConditionalExecution struct {
// contains filtered or unexported fields
}
ConditionalExecution executes actions based on conditions
func NewConditionalExecution ¶ added in v0.2.0
func NewConditionalExecution() *ConditionalExecution
NewConditionalExecution creates a new ConditionalExecution
Returns:
- *ConditionalExecution: a new instance of ConditionalExecution
Example usage:
ce := gonuts.NewConditionalExecution(). If(func() bool { return x > 10 }). Then(func() { fmt.Println("x is greater than 10") }). ElseIf(func() bool { return x > 5 }). Then(func() { fmt.Println("x is greater than 5 but not greater than 10") }). Else(func() { fmt.Println("x is 5 or less") }). Execute()
func (*ConditionalExecution) Else ¶ added in v0.2.0
func (ce *ConditionalExecution) Else(action Action) *ConditionalExecution
Else adds an action to be executed if all conditions are false
Parameters:
- action: a function to be executed
Returns:
- *ConditionalExecution: the ConditionalExecution instance for method chaining
func (*ConditionalExecution) ElseIf ¶ added in v0.2.0
func (ce *ConditionalExecution) ElseIf(condition Condition) *ConditionalExecution
ElseIf is an alias for If to improve readability
Parameters:
- condition: a function that returns a boolean
Returns:
- *ConditionalExecution: the ConditionalExecution instance for method chaining
func (*ConditionalExecution) Execute ¶ added in v0.2.0
func (ce *ConditionalExecution) Execute()
Execute runs the conditional execution chain
This method evaluates each condition in order and executes the corresponding action for the first true condition. If no conditions are true and an Else action is defined, it executes the Else action.
func (*ConditionalExecution) ExecuteWithFallthrough ¶ added in v0.2.0
func (ce *ConditionalExecution) ExecuteWithFallthrough()
ExecuteWithFallthrough runs the conditional execution chain with fallthrough behavior
This method is similar to Execute, but it continues to evaluate conditions and execute actions even after a true condition is found, until it encounters a condition that returns false or reaches the end of the chain.
func (*ConditionalExecution) If ¶ added in v0.2.0
func (ce *ConditionalExecution) If(condition Condition) *ConditionalExecution
If adds a condition to the execution chain
Parameters:
- condition: a function that returns a boolean
Returns:
- *ConditionalExecution: the ConditionalExecution instance for method chaining
func (*ConditionalExecution) Then ¶ added in v0.2.0
func (ce *ConditionalExecution) Then(action Action) *ConditionalExecution
Then adds an action to be executed if the previous condition is true
Parameters:
- action: a function to be executed
Returns:
- *ConditionalExecution: the ConditionalExecution instance for method chaining
type ErrorPlus ¶ added in v0.3.1
type ErrorPlus struct {
// contains filtered or unexported fields
}
ErrorPlus represents an extended error type that includes an error message, an error code, additional context, stack trace, and the original wrapped error. It is designed to be immutable and thread-safe. Example usage of ErrorPlus with context and logging.
func example() { err := errors.New("database connection failed") errPlus := NewInternalError("Unable to reach the database", err). WithContext("userID", 1234). WithContext("retry", true) errPlus.Log() }
func NewBadRequestError ¶ added in v0.3.1
NewBadRequestError creates a new ErrorPlus representing a 400 Bad Request error.
func NewErrorPlus ¶ added in v0.3.1
NewErrorPlus creates a new ErrorPlus instance by wrapping an error with a custom message and code. It captures the stack trace at the point of creation.
func NewInternalError ¶ added in v0.3.1
NewInternalError creates a new ErrorPlus representing a 500 Internal Server Error.
func NewNotFoundError ¶ added in v0.3.1
NewNotFoundError creates a new ErrorPlus representing a 404 Not Found error.
func NewUnauthorizedError ¶ added in v0.3.1
NewUnauthorizedError creates a new ErrorPlus representing a 401 Unauthorized error.
func (*ErrorPlus) As ¶ added in v0.3.1
As attempts to map the ErrorPlus to a target error type, useful for type assertion.
func (*ErrorPlus) Context ¶ added in v0.3.1
Context returns the additional context associated with the ErrorPlus.
func (*ErrorPlus) ContextStr ¶ added in v0.3.3
ErrorStr returns the error message as a string.
func (*ErrorPlus) Error ¶ added in v0.3.1
Error implements the error interface, returning the error message including context and original error.
func (*ErrorPlus) Format ¶ added in v0.3.1
Format implements the fmt.Formatter interface for custom formatting.
func (*ErrorPlus) Is ¶ added in v0.3.1
Is compares the ErrorPlus with another target error, checking if the underlying error matches.
func (*ErrorPlus) Log ¶ added in v0.3.1
func (e *ErrorPlus) Log()
Log logs the error using the configured logger.
func (*ErrorPlus) MarshalJSON ¶ added in v0.3.1
MarshalJSON implements the json.Marshaler interface, allowing custom JSON serialization.
func (*ErrorPlus) Msg ¶ added in v0.3.3
ErrorMsg returns the error message without the original error.
func (*ErrorPlus) StackTrace ¶ added in v0.3.1
StackTrace returns the stack trace associated with the error.
func (*ErrorPlus) Timestamp ¶ added in v0.3.1
Timestamp returns the time when the error was created.
func (*ErrorPlus) Unwrap ¶ added in v0.3.1
Unwrap returns the underlying original error, allowing access to the original error for further handling.
func (*ErrorPlus) WithCode ¶ added in v0.3.1
WithCode returns a new ErrorPlus with the provided code, preserving immutability.
func (*ErrorPlus) WithContext ¶ added in v0.3.1
WithContext returns a new ErrorPlus with the additional context, preserving immutability.
type EventData ¶ added in v0.3.4
EventData encapsulates event information passed to the state machine.
type EventEmitter ¶ added in v0.2.0
type EventEmitter struct {
// contains filtered or unexported fields
}
EventEmitter is a flexible publish-subscribe event system with named listeners
func NewEventEmitter ¶ added in v0.2.0
func NewEventEmitter() *EventEmitter
NewEventEmitter creates a new EventEmitter
Returns:
- *EventEmitter: a new instance of EventEmitter
Example usage:
emitter := gonuts.NewEventEmitter()
func (*EventEmitter) Emit ¶ added in v0.2.0
func (ee *EventEmitter) Emit(event string, args ...interface{}) error
Emit triggers an event with the given arguments
Parameters:
- event: the name of the event to emit
- args: the arguments to pass to the event listeners
Returns:
- error: any error that occurred during emission
func (*EventEmitter) EmitConcurrent ¶ added in v0.2.0
func (ee *EventEmitter) EmitConcurrent(event string, args ...interface{}) error
EmitConcurrent triggers an event with the given arguments, calling listeners concurrently
Parameters:
- event: the name of the event to emit
- args: the arguments to pass to the event listeners
Returns:
- error: any error that occurred during emission
func (*EventEmitter) Events ¶ added in v0.2.0
func (ee *EventEmitter) Events() []string
Events returns a list of all events that have listeners
Returns:
- []string: a slice containing all events with listeners
func (*EventEmitter) ListenerCount ¶ added in v0.2.0
func (ee *EventEmitter) ListenerCount(event string) int
ListenerCount returns the number of listeners for a given event
Parameters:
- event: the name of the event
Returns:
- int: the number of listeners for the event
func (*EventEmitter) ListenerNames ¶ added in v0.2.0
func (ee *EventEmitter) ListenerNames(event string) []string
ListenerNames returns a list of all listener names for a given event
Parameters:
- event: the name of the event
Returns:
- []string: a slice containing all listener names for the event
func (*EventEmitter) Off ¶ added in v0.2.0
func (ee *EventEmitter) Off(event, name string) error
Off unsubscribes a named function from an event
Parameters:
- event: the name of the event to unsubscribe from
- name: the name or ID of the listener to unsubscribe
Returns:
- error: any error that occurred during unsubscription
func (*EventEmitter) On ¶ added in v0.2.0
func (ee *EventEmitter) On(event, name string, fn interface{}) (string, error)
On subscribes a named function to an event
Parameters:
- event: the name of the event to subscribe to
- name: a unique name for this listener (if empty, a unique ID will be generated)
- fn: the function to be called when the event is emitted
Returns:
- string: the name or generated ID of the listener
- error: any error that occurred during subscription
Example usage:
id, err := emitter.On("userLoggedIn", "logLoginTime", func(username string) { fmt.Printf("User logged in: %s at %v\n", username, time.Now()) }) if err != nil { log.Printf("Error subscribing to event: %v", err) }
func (*EventEmitter) Once ¶ added in v0.2.0
func (ee *EventEmitter) Once(event, name string, fn interface{}) (string, error)
Once subscribes a one-time named function to an event
Parameters:
- event: the name of the event to subscribe to
- name: a unique name for this listener (if empty, a unique ID will be generated)
- fn: the function to be called when the event is emitted
Returns:
- string: the name or generated ID of the listener
- error: any error that occurred during subscription
The function will be automatically unsubscribed after it is called once.
type GoInterval ¶ added in v0.1.3
type GoInterval struct {
// contains filtered or unexported fields
}
func Interval ¶
func Interval(call func() bool, duration time.Duration, runImmediately bool) *GoInterval
creates a new GoInteval struct that allows running a function on a regular interal. the call function can trigger a stop of the timer by returning false instead of true
func (*GoInterval) Start ¶ added in v0.1.3
func (iv *GoInterval) Start(duration time.Duration, runImmediately bool) *GoInterval
func (*GoInterval) State ¶ added in v0.1.3
func (iv *GoInterval) State() bool
func (*GoInterval) Stop ¶ added in v0.1.3
func (iv *GoInterval) Stop() *GoInterval
type JSONPathExtractor ¶ added in v0.2.0
type JSONPathExtractor struct {
// contains filtered or unexported fields
}
JSONPathExtractor extracts values from JSON data using a path-like syntax
func NewJSONPathExtractor ¶ added in v0.2.0
func NewJSONPathExtractor(jsonData string) (*JSONPathExtractor, error)
NewJSONPathExtractor creates a new JSONPathExtractor
Example:
jsonData := `{"name": "John", "age": 30, "address": {"city": "New York"}}` extractor, err := NewJSONPathExtractor(jsonData) if err != nil { log.Fatal(err) }
func (*JSONPathExtractor) Extract ¶ added in v0.2.0
func (jpe *JSONPathExtractor) Extract(path string) (interface{}, error)
Extract retrieves a value from the JSON data using the given path
The path can include dot notation for nested objects, bracket notation for array indices, and wildcards (*) for matching multiple elements.
Example:
value, err := extractor.Extract("address.city") if err != nil { log.Fatal(err) } fmt.Println(value) // Output: New York
func (*JSONPathExtractor) ExtractArray ¶ added in v0.2.0
func (jpe *JSONPathExtractor) ExtractArray(path string) ([]interface{}, error)
ExtractArray is a convenience method that extracts an array value
func (*JSONPathExtractor) ExtractBool ¶ added in v0.2.0
func (jpe *JSONPathExtractor) ExtractBool(path string) (bool, error)
ExtractBool is a convenience method that extracts a bool value
func (*JSONPathExtractor) ExtractFloat ¶ added in v0.2.0
func (jpe *JSONPathExtractor) ExtractFloat(path string) (float64, error)
ExtractFloat is a convenience method that extracts a float64 value
func (*JSONPathExtractor) ExtractInt ¶ added in v0.2.0
func (jpe *JSONPathExtractor) ExtractInt(path string) (int, error)
ExtractInt is a convenience method that extracts an int value
func (*JSONPathExtractor) ExtractMultiple ¶ added in v0.2.0
func (jpe *JSONPathExtractor) ExtractMultiple(paths ...string) (map[string]interface{}, error)
ExtractMultiple extracts multiple values from the JSON data using the given paths
Example:
values, err := extractor.ExtractMultiple("name", "age", "address.city") if err != nil { log.Fatal(err) } fmt.Println(values) // Output: map[name:John age:30 address.city:New York]
func (*JSONPathExtractor) ExtractString ¶ added in v0.2.0
func (jpe *JSONPathExtractor) ExtractString(path string) (string, error)
ExtractString is a convenience method that extracts a string value
Example:
name, err := extractor.ExtractString("name") if err != nil { log.Fatal(err) } fmt.Println(name) // Output: John
type MapFunc ¶ added in v0.2.0
type MapFunc[T, R any] func(T) R
MapFunc is a function that transforms an input value into an output value
type MarkdownGeneratorConfig ¶ added in v0.2.0
type MarkdownGeneratorConfig struct { BaseDir *string `yaml:"baseDir"` Includes []string `yaml:"includes"` Excludes []string `yaml:"excludes"` BaseHeaderLevel *int `yaml:"baseHeaderLevel"` PrependText *string `yaml:"prependText"` Title *string `yaml:"title"` OutputFile *string `yaml:"outputFile"` }
func LoadConfigFromYAML ¶ added in v0.2.0
func LoadConfigFromYAML(filename string) (*MarkdownGeneratorConfig, error)
type MemoizedFunc ¶ added in v0.2.0
type MemoizedFunc struct {
// contains filtered or unexported fields
}
MemoizedFunc is a wrapper for a memoized function
func Memoize ¶ added in v0.2.0
func Memoize(f interface{}, ttl time.Duration) *MemoizedFunc
Memoize creates a memoized version of the given function
Parameters:
- f: the function to memoize (must be a function type)
- ttl: time-to-live for cached results (use 0 for no expiration)
Returns:
- *MemoizedFunc: a memoized version of the input function
The memoized function will cache results based on input parameters. Subsequent calls with the same parameters will return the cached result. Cached results expire after the specified TTL (if non-zero).
Example usage:
expensiveFunc := func(x int) int { time.Sleep(time.Second) // Simulate expensive operation return x * 2 } memoized := gonuts.Memoize(expensiveFunc, 5*time.Minute) start := time.Now() result, err := memoized.Call(42) fmt.Printf("First call took %v: %v\n", time.Since(start), result) start = time.Now() result, err = memoized.Call(42) fmt.Printf("Second call took %v: %v\n", time.Since(start), result)
func (*MemoizedFunc) Call ¶ added in v0.2.0
func (m *MemoizedFunc) Call(args ...interface{}) (interface{}, error)
Call invokes the memoized function with the given arguments
Parameters:
- args: the arguments to pass to the memoized function
Returns:
- interface{}: the result of the function call
- error: any error that occurred during the function call or type checking
type PaginationInfo ¶ added in v0.2.0
type PaginationInfo struct { CurrentPage int `json:"current_page"` PerPage int `json:"per_page"` TotalItems int64 `json:"total_items"` TotalPages int `json:"total_pages"` FirstItem int `json:"first_item"` LastItem int `json:"last_item"` FirstPage int `json:"first_page"` LastPage int `json:"last_page"` NextPage *int `json:"next_page"` PreviousPage *int `json:"previous_page"` }
PaginationInfo contains information about the current pagination state
func NewPaginationInfo ¶ added in v0.2.0
func NewPaginationInfo(currentPage, perPage int, totalItems int64) *PaginationInfo
NewPaginationInfo creates a new PaginationInfo instance
Parameters:
- currentPage: the current page number
- perPage: the number of items per page
- totalItems: the total number of items in the dataset
Returns:
- *PaginationInfo: a new instance of PaginationInfo
Example usage:
pagination := gonuts.NewPaginationInfo(2, 10, 95) fmt.Printf("Current Page: %d\n", pagination.CurrentPage) fmt.Printf("Total Pages: %d\n", pagination.TotalPages) fmt.Printf("Next Page: %v\n", *pagination.NextPage) // Output: // Current Page: 2 // Total Pages: 10 // Next Page: 3
func (*PaginationInfo) HasNextPage ¶ added in v0.2.0
func (p *PaginationInfo) HasNextPage() bool
HasNextPage checks if there is a next page
Returns:
- bool: true if there is a next page, false otherwise
func (*PaginationInfo) HasPreviousPage ¶ added in v0.2.0
func (p *PaginationInfo) HasPreviousPage() bool
HasPreviousPage checks if there is a previous page
Returns:
- bool: true if there is a previous page, false otherwise
func (*PaginationInfo) Limit ¶ added in v0.2.0
func (p *PaginationInfo) Limit() int
Limit returns the number of items per page
Returns:
- int: the number of items per page
func (*PaginationInfo) Offset ¶ added in v0.2.0
func (p *PaginationInfo) Offset() int
Offset calculates the offset for database queries
Returns:
- int: the offset to use in database queries
func (*PaginationInfo) PageNumbers ¶ added in v0.2.0
func (p *PaginationInfo) PageNumbers(max int) []int
PageNumbers returns a slice of page numbers to display
Parameters:
- max: the maximum number of page numbers to return
Returns:
- []int: a slice of page numbers
This method is useful for generating pagination controls in user interfaces. It aims to provide a balanced range of page numbers around the current page.
func (*PaginationInfo) String ¶ added in v0.2.0
func (p *PaginationInfo) String() string
String returns a string representation of the pagination info
Returns:
- string: a string representation of the pagination info
type RateLimiter ¶ added in v0.2.0
type RateLimiter struct {
// contains filtered or unexported fields
}
RateLimiter implements a token bucket rate limiter
func NewRateLimiter ¶ added in v0.2.0
func NewRateLimiter(rate, bucketSize float64) *RateLimiter
NewRateLimiter creates a new RateLimiter
Parameters:
- rate: the rate at which tokens are added to the bucket (per second)
- bucketSize: the maximum number of tokens the bucket can hold
Returns:
- *RateLimiter: a new instance of RateLimiter
Example usage:
limiter := gonuts.NewRateLimiter(10, 100) // 10 tokens per second, max 100 tokens for i := 0; i < 1000; i++ { if limiter.Allow() { // Perform rate-limited operation fmt.Println("Operation allowed:", i) } else { fmt.Println("Operation throttled:", i) } time.Sleep(time.Millisecond * 50) // Simulate some work }
func (*RateLimiter) Allow ¶ added in v0.2.0
func (rl *RateLimiter) Allow() bool
Allow checks if a request is allowed under the rate limit
Returns:
- bool: true if the request is allowed, false otherwise
func (*RateLimiter) AllowN ¶ added in v0.2.0
func (rl *RateLimiter) AllowN(n float64) bool
AllowN checks if n requests are allowed under the rate limit
Parameters:
- n: the number of tokens to request
Returns:
- bool: true if the requests are allowed, false otherwise
func (*RateLimiter) Wait ¶ added in v0.2.0
func (rl *RateLimiter) Wait(ctx context.Context) error
Wait blocks until a request is allowed or the context is cancelled
Parameters:
- ctx: a context for cancellation
Returns:
- error: nil if a token was acquired, or an error if the context was cancelled
Example usage:
ctx, cancel := context.WithTimeout(context.Background(), time.Second) defer cancel() err := limiter.Wait(ctx) if err != nil { fmt.Println("Failed to acquire token:", err) return } // Perform rate-limited operation
func (*RateLimiter) WaitN ¶ added in v0.2.0
func (rl *RateLimiter) WaitN(ctx context.Context, n float64) error
WaitN blocks until n requests are allowed or the context is cancelled
Parameters:
- ctx: a context for cancellation
- n: the number of tokens to request
Returns:
- error: nil if tokens were acquired, or an error if the context was cancelled
type ReduceFunc ¶ added in v0.2.0
type ReduceFunc[R any] func(R, R) R
ReduceFunc is a function that combines two values into a single value
type SMAction ¶ added in v0.2.0
type SMAction func(context map[string]interface{})
SMAction represents a function to be executed during state transitions.
type SMCondition ¶ added in v0.2.0
SMCondition represents a function that returns a boolean based on the context.
type Set ¶ added in v0.2.0
type Set[T comparable] struct { // contains filtered or unexported fields }
Set is a generic set data structure
func NewSet ¶ added in v0.2.0
func NewSet[T comparable]() *Set[T]
NewSet creates a new Set
Returns:
- *Set[T]: a new instance of Set
Example usage:
intSet := gonuts.NewSet[int]() intSet.Add(1, 2, 3) fmt.Println(intSet.Contains(2)) // Output: true stringSet := gonuts.NewSet[string]() stringSet.Add("apple", "banana", "cherry") fmt.Println(stringSet.Size()) // Output: 3
func (*Set[T]) Add ¶ added in v0.2.0
Add adds items to the set
Parameters:
- items: the items to add to the set
Returns:
- *Set[T]: the Set instance for method chaining
func (*Set[T]) Clear ¶ added in v0.2.0
func (s *Set[T]) Clear()
Clear removes all items from the set
func (*Set[T]) Contains ¶ added in v0.2.0
Contains checks if an item is in the set
Parameters:
- item: the item to check for
Returns:
- bool: true if the item is in the set, false otherwise
func (*Set[T]) Difference ¶ added in v0.2.0
Difference returns a new set that is the difference of this set and another set
Parameters:
- other: the other set to diff with
Returns:
- *Set[T]: a new Set containing the difference of this set minus the other set
func (*Set[T]) Intersection ¶ added in v0.2.0
Intersection returns a new set that is the intersection of this set and another set
Parameters:
- other: the other set to intersect with
Returns:
- *Set[T]: a new Set containing the intersection of both sets
func (*Set[T]) Remove ¶ added in v0.2.0
Remove removes items from the set
Parameters:
- items: the items to remove from the set
Returns:
- *Set[T]: the Set instance for method chaining
func (*Set[T]) Size ¶ added in v0.2.0
Size returns the number of items in the set
Returns:
- int: the number of items in the set
func (*Set[T]) String ¶ added in v0.2.0
String returns a string representation of the set
Returns:
- string: a string representation of the set
type StateID ¶ added in v0.2.0
type StateID string
StateID is a unique identifier for a state.
const AnyState StateID = "*"
AnyState represents a wildcard state that matches any current state.
type StatesMan ¶ added in v0.2.0
type StatesMan struct { Name string States map[StateID]*State Transitions []Transition TimedTransitions []TimedTransition CurrentState StateID EventChannel chan EventData Context map[string]interface{} PreHooks []SMAction PostHooks []SMAction // contains filtered or unexported fields }
StatesMan is a flexible, concurrent-safe state machine manager.
func NewStatesMan ¶ added in v0.2.0
NewStatesMan creates a new StatesMan instance.
func (*StatesMan) AddPostHook ¶ added in v0.2.0
AddPostHook adds a post-transition hook.
func (*StatesMan) AddPreHook ¶ added in v0.2.0
AddPreHook adds a pre-transition hook.
func (*StatesMan) AddTimedTransition ¶ added in v0.2.0
func (sm *StatesMan) AddTimedTransition(from, to StateID, duration time.Duration, actions ...SMAction)
AddTimedTransition adds a new timed transition to the state machine.
func (*StatesMan) AddTransition ¶ added in v0.2.0
func (sm *StatesMan) AddTransition(from, to StateID, event EventID, condition SMCondition, actions ...SMAction)
AddTransition adds a new transition to the state machine.
func (*StatesMan) GenerateDOT ¶ added in v0.2.0
GenerateDOT generates a DOT representation of the state machine for visualization.
func (*StatesMan) GetCurrentState ¶ added in v0.2.0
GetCurrentState returns the current state of the state machine.
func (*StatesMan) Import ¶ added in v0.2.0
Import imports the state machine configuration from JSON.
func (*StatesMan) Run ¶ added in v0.2.0
func (sm *StatesMan) Run()
Run starts the state machine event loop.
func (*StatesMan) SetInitialState ¶ added in v0.2.0
SetInitialState sets the initial state of the state machine.
func (*StatesMan) TriggerEvent ¶ added in v0.2.0
TriggerEvent triggers an event in the state machine without knowing the next state.
type TimedTransition ¶ added in v0.2.0
type TimedTransition struct { Transition Duration time.Duration // contains filtered or unexported fields }
TimedTransition represents a transition that occurs after a specified duration.
type Transition ¶ added in v0.2.0
type Transition struct { From StateID To StateID Event EventID Condition SMCondition Actions []SMAction }
Transition represents a transition between states.
type Trie ¶ added in v0.2.0
type Trie struct {
// contains filtered or unexported fields
}
Trie is a tree-like data structure for efficient string operations.
func NewTrie ¶ added in v0.2.0
func NewTrie() *Trie
NewTrie creates and returns a new Trie.
Example:
trie := NewTrie()
func (*Trie) AutoComplete ¶ added in v0.2.0
AutoComplete returns a list of words that start with the given prefix.
Example:
trie := NewTrie() trie.BulkInsert([]string{"apple", "app", "application", "appreciate"}) suggestions := trie.AutoComplete("app", 3) fmt.Println(suggestions) // Output: [app apple application]
func (*Trie) BulkInsert ¶ added in v0.2.0
BulkInsert efficiently inserts multiple words into the Trie.
Example:
trie := NewTrie() words := []string{"apple", "app", "application"} trie.BulkInsert(words)
func (*Trie) Insert ¶ added in v0.2.0
Insert adds a word to the Trie.
Example:
trie := NewTrie() trie.Insert("apple")
func (*Trie) InsertWithValue ¶ added in v0.2.0
InsertWithValue adds a word to the Trie with an associated value.
Example:
trie := NewTrie() trie.InsertWithValue("apple", 42)
func (*Trie) LongestCommonPrefix ¶ added in v0.2.0
LongestCommonPrefix finds the longest common prefix of all words in the Trie.
Example:
trie := NewTrie() trie.BulkInsert([]string{"flower", "flow", "flight"}) fmt.Println(trie.LongestCommonPrefix()) // Output: "fl"
func (*Trie) Search ¶ added in v0.2.0
Search checks if a word exists in the Trie.
Example:
trie := NewTrie() trie.Insert("apple") fmt.Println(trie.Search("apple")) // Output: true fmt.Println(trie.Search("app")) // Output: false
func (*Trie) StartsWith ¶ added in v0.2.0
StartsWith checks if any word in the Trie starts with the given prefix.
Example:
trie := NewTrie() trie.Insert("apple") fmt.Println(trie.StartsWith("app")) // Output: true fmt.Println(trie.StartsWith("ban")) // Output: false
func (*Trie) WildcardSearch ¶ added in v0.2.0
WildcardSearch searches for words matching a pattern with wildcards. The '.' character in the pattern matches any single character.
Example:
trie := NewTrie() trie.BulkInsert([]string{"cat", "dog", "rat"}) matches := trie.WildcardSearch("r.t") fmt.Println(matches) // Output: [rat]
type TrieNode ¶ added in v0.2.0
type TrieNode struct {
// contains filtered or unexported fields
}
TrieNode represents a node in the Trie data structure.
type URLBuilder ¶ added in v0.2.0
type URLBuilder struct {
// contains filtered or unexported fields
}
URLBuilder provides a fluent interface for constructing URLs
func NewURLBuilder ¶ added in v0.2.0
func NewURLBuilder(baseURL string) (*URLBuilder, error)
NewURLBuilder creates a new URLBuilder
Example:
builder := NewURLBuilder("https://api.example.com")
func ParseURL ¶ added in v0.2.0
func ParseURL(rawURL string) (*URLBuilder, error)
ParseURL parses a URL string and returns a new URLBuilder
Example:
builder, err := ParseURL("https://api.example.com/v1/users?page=1") if err != nil { log.Fatal(err) }
func (*URLBuilder) AddPath ¶ added in v0.2.0
func (b *URLBuilder) AddPath(segment string) *URLBuilder
AddPath adds a path segment to the URL
Example:
builder.AddPath("v1").AddPath("users")
func (*URLBuilder) AddQuery ¶ added in v0.2.0
func (b *URLBuilder) AddQuery(key, value string) *URLBuilder
AddQuery adds a query parameter to the URL
Example:
builder.AddQuery("page", "1").AddQuery("limit", "10")
func (*URLBuilder) Build ¶ added in v0.2.0
func (b *URLBuilder) Build() string
Build constructs and returns the final URL as a string
Example:
url := builder.Build() fmt.Println(url) // https://api.example.com/v1/users?page=1&limit=10#section1
func (*URLBuilder) BuildURL ¶ added in v0.2.0
func (b *URLBuilder) BuildURL() (*url.URL, error)
BuildURL constructs and returns the final URL as a *url.URL
Example:
urlObj, err := builder.BuildURL() if err != nil { log.Fatal(err) } fmt.Println(urlObj.String())
func (*URLBuilder) Clone ¶ added in v0.2.0
func (b *URLBuilder) Clone() *URLBuilder
Clone creates a deep copy of the URLBuilder
Example:
newBuilder := builder.Clone()
func (*URLBuilder) RemoveQuery ¶ added in v0.2.0
func (b *URLBuilder) RemoveQuery(key string) *URLBuilder
RemoveQuery removes a query parameter from the URL
Example:
builder.RemoveQuery("page")
func (*URLBuilder) SetCredentials ¶ added in v0.2.0
func (b *URLBuilder) SetCredentials(username, password string) *URLBuilder
SetCredentials sets the username and password for basic auth
Example:
builder.SetCredentials("username", "password")
func (*URLBuilder) SetFragment ¶ added in v0.2.0
func (b *URLBuilder) SetFragment(fragment string) *URLBuilder
SetFragment sets the fragment (hash) of the URL
Example:
builder.SetFragment("section1")
func (*URLBuilder) SetHost ¶ added in v0.2.0
func (b *URLBuilder) SetHost(host string) *URLBuilder
SetHost sets the host of the URL
Example:
builder.SetHost("api.example.com")
func (*URLBuilder) SetPath ¶ added in v0.2.0
func (b *URLBuilder) SetPath(path string) *URLBuilder
SetPath sets the complete path, overwriting any existing path
Example:
builder.SetPath("/v1/users")
func (*URLBuilder) SetPort ¶ added in v0.2.0
func (b *URLBuilder) SetPort(port string) *URLBuilder
SetPort sets the port of the URL
Example:
builder.SetPort("8080")
func (*URLBuilder) SetQuery ¶ added in v0.2.0
func (b *URLBuilder) SetQuery(key, value string) *URLBuilder
SetQuery sets a query parameter, overwriting any existing values for the key
Example:
builder.SetQuery("page", "1")
func (*URLBuilder) SetScheme ¶ added in v0.2.0
func (b *URLBuilder) SetScheme(scheme string) *URLBuilder
SetScheme sets the scheme (protocol) of the URL
Example:
builder.SetScheme("https")
type VersionData ¶ added in v0.2.0
type VersionData struct { Version string `json:"version"` GitCommit string `json:"gitCommit"` GitBranch string `json:"gitBranch"` }
func GetVersionData ¶ added in v0.2.0
func GetVersionData() VersionData
Source Files ¶
- main.go
- nuts.ErrorPlus.go
- nuts.byteskilomega.go
- nuts.circuitbreaker.go
- nuts.commandlineparameters.go
- nuts.concurrentmap.go
- nuts.conditionalexec.go
- nuts.debounce.go
- nuts.eventemitter.go
- nuts.filterjsonfields.go
- nuts.ids.go
- nuts.interval.go
- nuts.jsonpath.go
- nuts.logger.go
- nuts.mapreduce.go
- nuts.memoization.go
- nuts.pagination.go
- nuts.passwords.go
- nuts.pointerstovalues.go
- nuts.processstats.go
- nuts.projectmarkdown.go
- nuts.ratelimiter.go
- nuts.retry.go
- nuts.safecast.go
- nuts.sanitize.go
- nuts.sets.go
- nuts.slicehelpers.go
- nuts.statesman.go
- nuts.stringSlice.go
- nuts.timestamps.go
- nuts.trie.go
- nuts.urlbuilder.go
- nuts.version.go