gonuts

package module
v0.3.4 Latest Latest
Warning

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

Go to latest
Published: Oct 12, 2024 License: Unlicense Imports: 30 Imported by: 2

README

go-nuts

go-nuts is a versatile Go package that provides a collection of utility functions and types to simplify common programming tasks. It offers functionalities ranging from ID generation to logging, state management, concurrency helpers, and more. go-"nuts" stands for "n-utilities".

Installation

To install go-nuts, use the following command:

go get github.com/vaudience/go-nuts

we alias the package to nuts in our code.

import (
    nuts "github.com/vaudience/go-nuts"
)

Functionality Overview

ID Generation
NanoID(prefix string) string

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.

Example:

id := nuts.NanoID("user")
fmt.Println(id) // Output: user_6ByTSYmGzT2c
NID(prefix string, length int) string

Generates a unique ID with a specified length and optional prefix. It creates a unique identifier of the given length using a predefined alphabet. If a prefix is provided, it's prepended to the generated ID.

Example:

id := nuts.NID("doc", 8)
fmt.Println(id) // Output: doc_r3tM9wK1
GenerateRandomString(chars []rune, length int) string

Creates a random string of a given length using the provided character set.

Example:

chars := []rune("abcdefghijklmnopqrstuvwxyz")
randomStr := nuts.GenerateRandomString(chars, 10)
fmt.Println(randomStr) // Output: (a random 10-character string using the given alphabet)
Logging
L *zap.SugaredLogger

L is a pre-initialized logger using the zap logging library. It provides a convenient way to log messages at various levels throughout your application.

Example:

nuts.L.Info("This is an info message")
nuts.L.Debug("This is a debug message")
nuts.L.Error("This is an error message")
Init_Logger(targetLevel zapcore.Level, instanceId string, log2file bool, logfilePath string) *zap.SugaredLogger

Initializes a new logger with the specified configuration.

SetLoglevel(loglevel string, instanceId string, log2file bool, logfilePath string)

Sets the log level for the logger. Available log levels are "DEBUG", "INFO", "WARN", "ERROR", "FATAL", and "PANIC".

Example:

nuts.SetLoglevel("DEBUG", "myapp", true, "/var/log/myapp/")
SyslogTimeEncoder(t time.Time, enc zapcore.PrimitiveArrayEncoder)

A custom time encoder for the logger that formats time in syslog format.

GetPrettyJson(object any) string

Converts an object to a pretty-printed JSON string.

Concurrent Data Structures
ConcurrentMap[K comparable, V any]

A thread-safe map implementation that supports concurrent read and write operations.

Example:

cm := nuts.NewConcurrentMap[string, int](16)
cm.Set("key", 42)
value, exists := cm.Get("key")

Methods include:

  • Set(key K, value V)
  • Get(key K) (V, bool)
  • Delete(key K)
  • Len() int
  • Clear()
  • Keys() []K
  • Values() []V
  • Range(f func(K, V) bool)
  • GetOrSet(key K, value V) (V, bool)
  • SetIfAbsent(key K, value V) bool
Errors
ErrorPlus

ErrorPlus is an enhanced error type provided by the gonuts package, designed to offer robust and structured error handling in Go applications. It encapsulates the original error with additional context, error codes, stack traces, and logging integration, while ensuring immutability and thread safety.

Key Features
  • Immutability and Thread Safety: All methods return new instances, ensuring that errors are immutable and safe to use across goroutines.
  • Custom Error Codes: Supports custom error codes, including HTTP status codes or application-specific codes.
  • Contextual Data: Allows attaching arbitrary key-value pairs to the error for additional context.
  • Stack Trace Capture: Automatically captures the stack trace at the point where the error is created.
  • Logging Integration: Seamlessly integrates with the gonuts logging system (gonuts.L) by default but allows for custom logger injection.
  • Error Cause Chains: Supports error wrapping and unwrapping, compatible with Go's standard error handling mechanisms.
  • JSON Serialization: Implements custom JSON marshaling to serialize the error, including context and stack trace.
  • Custom Formatting: Implements the fmt.Formatter interface for customizable error output.
Creating an ErrorPlus Instance

To create a new ErrorPlus instance, use the NewErrorPlus function:

err := errors.New("database connection failed")
errPlus := nuts.NewErrorPlus(err, "Unable to reach the database", 500)
Adding Contextual Information

You can enrich the error with additional context using the WithContext method:

errPlus = errPlus.WithContext("userID", 1234).
                  WithContext("operation", "fetchUser")

Each call to WithContext returns a new ErrorPlus instance, preserving immutability.

Using Helper Functions for Common HTTP Errors

ErrorPlus provides helper functions to create errors with common HTTP status codes:

  • NewNotFoundError(msg string, err error) *ErrorPlus
  • NewInternalError(msg string, err error) *ErrorPlus
  • NewUnauthorizedError(msg string, err error) *ErrorPlus
  • NewBadRequestError(msg string, err error) *ErrorPlus

Example:

err := errors.New("resource not found")
errPlus := nuts.NewNotFoundError("User does not exist", err)
Logging the Error

By default, ErrorPlus uses the gonuts.L logger for logging:

errPlus.Log()

You can inject a custom logger if needed:

customLogger := zap.NewExample().Sugar()
nuts.SetErrorLogger(customLogger)
errPlus.Log()
Accessing Error Information
  • Error Message: errPlus.Error()
  • Error Code: errPlus.Code()
  • Context: errPlus.Context()
  • Stack Trace: errPlus.StackTrace()
  • Timestamp: errPlus.Timestamp()

Example:

fmt.Println("Error Code:", errPlus.Code())
fmt.Println("Context:", errPlus.Context())
fmt.Println("Stack Trace:", errPlus.StackTrace())
Compatibility with Standard Error Handling

ErrorPlus is fully compatible with Go's standard error handling mechanisms:

  • Unwrapping Errors:

    if errors.Is(errPlus, sql.ErrNoRows) {
        // Handle "no rows" error
    }
    
  • Type Assertions:

    var pathError *os.PathError
    if errors.As(errPlus, &pathError) {
        // Handle specific path-related error
    }
    
Custom Formatting

ErrorPlus implements the fmt.Formatter interface, allowing for detailed formatting:

  • Default Format (%v or %s):

    fmt.Printf("%v\n", errPlus)
    // Output: Unable to reach the database: database connection failed
    
  • Detailed Format (%+v):

    fmt.Printf("%+v\n", errPlus)
    /* Output:
    ErrorPlus:
      Msg: Unable to reach the database
      Code: 500
      Error: database connection failed
      Context: map[userID:1234 operation:fetchUser]
      StackTrace:
    main.main
        /path/to/your/app/main.go:25
    runtime.main
        /usr/local/go/src/runtime/proc.go:225
    */
    
JSON Serialization

ErrorPlus can be serialized to JSON, including all its fields:

jsonData, err := json.Marshal(errPlus)
if err != nil {
    // Handle serialization error
}
fmt.Println(string(jsonData))

Sample JSON output:

{
  "msg": "Unable to reach the database",
  "code": 500,
  "context": {
    "userID": 1234,
    "operation": "fetchUser"
  },
  "stackTrace": [
    "main.main\n\t/path/to/your/app/main.go:25",
    "runtime.main\n\t/usr/local/go/src/runtime/proc.go:225"
  ],
  "timestamp": "2023-10-10T14:48:00Z",
  "error": "database connection failed"
}
Full API Reference
Creation Methods
  • NewErrorPlus(err error, msg string, code int) *ErrorPlus

    Creates a new ErrorPlus instance with the given error, message, and code.

  • Helper Functions for Common Errors

    • NewNotFoundError(msg string, err error) *ErrorPlus
    • NewInternalError(msg string, err error) *ErrorPlus
    • NewUnauthorizedError(msg string, err error) *ErrorPlus
    • NewBadRequestError(msg string, err error) *ErrorPlus
Modifier Methods (Immutable)
  • WithMsg(msg string) *ErrorPlus

    Returns a new ErrorPlus instance with the updated message.

  • WithCode(code int) *ErrorPlus

    Returns a new ErrorPlus instance with the updated code.

  • WithContext(key string, value interface{}) *ErrorPlus

    Returns a new ErrorPlus instance with additional context.

  • WithValues(msg string, code int) *ErrorPlus

    Returns a new ErrorPlus instance with updated message and code.

Accessor Methods
  • Error() string

    Implements the error interface.

  • Unwrap() error

    Returns the underlying error.

  • Is(target error) bool

    Checks if the target error matches the underlying error.

  • As(target interface{}) bool

    Attempts to map the ErrorPlus to a target error type.

  • Code() int

    Retrieves the error code.

  • Context() map[string]interface{}

    Retrieves a copy of the context map.

  • StackTrace() []string

    Retrieves the captured stack trace.

  • Timestamp() time.Time

    Retrieves the timestamp when the error was created.

Logging with ErrorPlus
  • Log()

    Logs the error using the configured logger.

  • SetErrorLogger(logger *zap.SugaredLogger)

    Sets a custom logger for all ErrorPlus instances.

Formatting and Serialization
  • Format(f fmt.State, c rune)

    Implements the fmt.Formatter interface for custom formatting.

  • MarshalJSON() ([]byte, error)

    Implements the json.Marshaler interface for JSON serialization.

Usage Example
package main

import (
    "database/sql"
    "errors"
    "fmt"

    nuts "github.com/vaudience/go-nuts"
)

func main() {
    // Simulate a database error
    baseErr := sql.ErrNoRows

    // Create an ErrorPlus instance
    errPlus := nuts.NewNotFoundError("User not found in the database", baseErr).
        WithContext("userID", 1234).
        WithContext("operation", "fetchUser")

    // Log the error
    errPlus.Log()

    // Check if the error is a sql.ErrNoRows
    if errors.Is(errPlus, sql.ErrNoRows) {
        fmt.Println("Handle the 'no rows' error")
    }

    // Print the error with detailed formatting
    fmt.Printf("%+v\n", errPlus)
}
Notes and Best Practices
  • Immutability: All modifier methods return new instances to ensure thread safety and prevent side effects.
  • Contextual Information: Use the WithContext method to add valuable debugging information.
  • Error Chaining: Utilize Unwrap, Is, and As to interact with the underlying error.
  • Logging: Leverage the Log method to integrate error logging seamlessly.
  • JSON Serialization: Be cautious when deserializing errors, as the original error type may not be fully reconstructed.
Integration with Other gonuts Features

ErrorPlus is designed to work harmoniously with other utilities provided by the gonuts package. For instance, you can use ErrorPlus alongside the EventEmitter for emitting errors or within StateMan for state transition errors.

State Management
StatesMan

A flexible state machine manager that supports complex state transitions, timed transitions, and hooks.

Example:

sm := nuts.NewStatesMan("TrafficLight")
sm.AddState("Red", "Red Light", []nuts.SMAction{func(ctx interface{}) { fmt.Println("Red light on") }}, nil)
sm.SetInitialState("Red")
sm.AddTransition("Red", "Green", "Next", nil)

Methods include:

  • AddState(id StateID, name string, entryActions, exitActions []SMAction)
  • AddChildState(parentID, childID StateID) error
  • SetInitialState(id StateID) error
  • AddTransition(from, to StateID, event EventID, condition SMCondition, actions ...SMAction)
  • AddTimedTransition(from, to StateID, duration time.Duration, actions ...SMAction)
  • TriggerEvent(event EventID)
  • AddPreHook(hook SMAction)
  • AddPostHook(hook SMAction)
  • Run()
  • GetCurrentState() StateID
  • Export() (string, error)
  • Import(jsonStr string) error
  • GenerateDOT() string
JSON Operations
RemoveJsonFields(obj any, fieldsToRemove []string) (string, error)

Removes specified fields from a JSON object.

Example:

jsonStr, err := nuts.RemoveJsonFields(myObj, []string{"sensitive_field", "internal_id"})
SelectJsonFields(obj any, fieldsToSelect []string) (string, error)

Selects only specified fields from a JSON object.

Example:

jsonStr, err := nuts.SelectJsonFields(myObj, []string{"name", "email", "age"})
Time Operations
TimeFromUnixTimestamp(timestamp int64) time.Time

Converts a Unix timestamp to a Go time.Time.

TimeFromJSTimestamp(timestamp int64) time.Time

Converts a JavaScript timestamp (milliseconds since epoch) to a Go time.Time.

TimeToJSTimestamp(t time.Time) int64

Converts a Go time.Time to a JavaScript timestamp.

Error Handling
CircuitBreaker

Implements the Circuit Breaker pattern for fault tolerance in distributed systems.

Example:

cb := nuts.NewCircuitBreaker(5, 10*time.Second, 2)
err := cb.Execute(func() error {
    return someRiskyOperation()
})

Methods include:

  • Execute(f func() error) error
  • State() CircuitBreakerState
  • LastError() error
Password Handling
NormalizePassword(p string) []byte

Converts a password string to a byte slice.

GeneratePassword(p string) string

Generates a hashed password using bcrypt.

ComparePasswords(hashedPwd string, inputPwd string) bool

Compares a hashed password with an input password.

Byte Size Formatting
BytesToNiceString(size int64) string

Converts a byte size to a human-readable string (e.g., KB, MB, GB).

BytesToKB/MB/GB/TB(size int64, digits int) float64

Converts bytes to kilobytes, megabytes, gigabytes, or terabytes.

Event Emitting
EventEmitter

A flexible publish-subscribe event system with named listeners.

Example:

emitter := nuts.NewEventEmitter()
emitter.On("userLoggedIn", "logLoginTime", func(username string) {
    fmt.Printf("User logged in: %s at %v\n", username, time.Now())
})
emitter.Emit("userLoggedIn", "JohnDoe")

Methods include:

  • On(event, name string, fn interface{}) (string, error)
  • Off(event, name string) error
  • Emit(event string, args ...interface{}) error
  • EmitConcurrent(event string, args ...interface{}) error
  • Once(event, name string, fn interface{}) (string, error)
  • ListenerCount(event string) int
  • ListenerNames(event string) []string
  • Events() []string
Trie Data Structure
Trie

An efficient tree-like data structure for string operations.

Example:

trie := nuts.NewTrie()
trie.Insert("apple")
fmt.Println(trie.Search("apple"))  // Output: true
fmt.Println(trie.StartsWith("app"))  // Output: true

Methods include:

  • Insert(word string)
  • InsertWithValue(word string, value interface{})
  • BulkInsert(words []string)
  • Search(word string) bool
  • StartsWith(prefix string) bool
  • AutoComplete(prefix string, limit int) []string
  • WildcardSearch(pattern string) []string
  • LongestCommonPrefix() string
Rate Limiting
RateLimiter

Implements a token bucket rate limiter.

Example:

limiter := nuts.NewRateLimiter(10, 100)  // 10 tokens per second, max 100 tokens
if limiter.Allow() {
    // Perform rate-limited operation
}

Methods include:

  • Allow() bool
  • AllowN(n float64) bool
  • Wait(ctx context.Context) error
  • WaitN(ctx context.Context, n float64) error
Retrying Operations
Retry(ctx context.Context, attempts int, initialDelay, maxDelay time.Duration, f func() error) error

Attempts to execute the given function with exponential backoff.

Example:

err := nuts.Retry(ctx, 5, time.Second, time.Minute, func() error {
    return someUnreliableOperation()
})
URL Building
URLBuilder

Provides a fluent interface for constructing URLs.

Example:

builder, _ := nuts.NewURLBuilder("https://api.example.com")
url := builder.AddPath("v1").AddPath("users").AddQuery("page", "1").Build()

Methods include:

  • SetScheme(scheme string) *URLBuilder
  • SetHost(host string) *URLBuilder
  • SetPort(port string) *URLBuilder
  • SetCredentials(username, password string) *URLBuilder
  • AddPath(segment string) *URLBuilder
  • SetPath(path string) *URLBuilder
  • AddQuery(key, value string) *URLBuilder
  • SetQuery(key, value string) *URLBuilder
  • RemoveQuery(key string) *URLBuilder
  • SetFragment(fragment string) *URLBuilder
  • Build() string
  • BuildURL() (*url.URL, error)
  • Clone() *URLBuilder
Parallel Processing
ParallelSliceMap[T, R any](ctx context.Context, input []T, mapFunc MapFunc[T, R]) ([]R, error)

Applies a function to each element of a slice concurrently.

ConcurrentMapReduce[T, R any](ctx context.Context, input []T, mapFunc MapFunc[T, R], reduceFunc ReduceFunc[R], initialValue R) (R, error)

Performs a map-reduce operation concurrently on the input slice.

Enum Generation
GenerateEnum(def EnumDefinition) (string, error)

Generates Go code for type-safe enums based on the provided definition.

WriteEnumToFile(def EnumDefinition, filename string) error

Generates enum code and writes it to a file.

Miscellaneous Utilities
Debounce(fn any, duration time.Duration, callback func(int)) func(...any)

Creates a debounced version of a function that delays its execution.

Interval(call func() bool, duration time.Duration, runImmediately bool) *GoInterval

Creates a new interval that runs a function on a regular interval.

PrintMemoryUsage() bool

Prints current memory usage statistics.

Set[T comparable]

A generic set data structure.

JSONPathExtractor

Extracts values from JSON data using a path-like syntax.

Example:

extractor, _ := nuts.NewJSONPathExtractor(jsonData)
value, _ := extractor.Extract("address.city")
Version Management
Init()

Initializes version data from a version.json file.

GetVersion() string

Returns the current version.

GetGitCommit() string

Returns the current Git commit hash.

GetGitBranch() string

Returns the current Git branch name.

GetVersionData() VersionData

Returns the complete version data structure.

Documentation

Overview

Package gonuts provides enhanced error handling functionality with structured error messages, error codes, context, stack trace support, and logging integration.

Index

Constants

View Source
const NID_Prefix_Separator = "_"

Variables

View Source
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")
)
View Source
var ErrCircuitOpen = errors.New("circuit breaker is open")

ErrCircuitOpen is returned when the circuit breaker is in the open state

View Source
var L = Init_Logger(zapcore.DebugLevel, "unknown", false, "logs/")
View Source
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 AssignToCastBoolOr(val any, fallbackVal bool) bool

func AssignToCastInt64Or

func AssignToCastInt64Or(val any, fallbackVal int64) int64

func AssignToCastStringOr

func AssignToCastStringOr(val any, fallbackVal string) string

func BoolPtr added in v0.2.0

func BoolPtr(b bool) *bool

BoolPtr returns a pointer to the given bool

func BytesToGB

func BytesToGB(size int64, digits int) (terrabytes float64)

func BytesToKB

func BytesToKB(size int64, digits int) (kilobytes float64)

func BytesToMB

func BytesToMB(size int64, digits int) (megabytes float64)

func BytesToNiceString

func BytesToNiceString(size int64) (formattedString string)

func BytesToTB

func BytesToTB(size int64, digits int) (terrabytes float64)

func Chunk added in v0.2.0

func Chunk[T any](slice []T, chunkSize int) [][]T

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

func ComparePasswords(hashedPwd string, inputPwd string) bool

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

func Debounce(fn any, duration time.Duration, callback func(int)) func(...any)

Debounce that executes first call immediately and last call after delays in calls

func Filter added in v0.2.0

func Filter[T any](slice []T, predicate func(T) bool) []T

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

func Float32Ptr(f float32) *float32

Float32Ptr returns a pointer to the given float32

func Float64Ptr added in v0.2.0

func Float64Ptr(f float64) *float64

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

func GeneratePassword(p string) string

GeneratePassword func for a making hash & salt with user password.

func GenerateRandomString

func GenerateRandomString(chars []rune, length int) string

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 GetPrettyJson(object any) (pretty string)

func GetVersion added in v0.2.0

func GetVersion() string

func IfThen added in v0.2.0

func IfThen(condition Condition, action Action)

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

func IfThenElse(condition Condition, thenAction, elseAction Action)

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 Int32Ptr added in v0.2.0

func Int32Ptr(i int32) *int32

Int32Ptr returns a pointer to the given int32

func Int64Ptr added in v0.2.0

func Int64Ptr(i int64) *int64

Int64Ptr returns a pointer to the given int64

func IntPtr added in v0.2.0

func IntPtr(i int) *int

IntPtr returns a pointer to the given int

func IsNID added in v0.3.0

func IsNID(id string, prefix string, length int) bool

IsNID checks if the given ID is a valid NID with the specified prefix and length.

func Join added in v0.2.0

func Join(slice []string, separator string) string

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

func NID(prefix string, length int) string

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

func NanoID(prefix string) string

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

func NormalizePassword(p string) []byte

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 Ptr added in v0.2.0

func Ptr[T any](v T) *T

Generic function to create a pointer to any type

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

func RemoveAt[T any](slice []T, index int) []T

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 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 Round

func Round(val float64, roundOn float64, places int) (newVal float64)

func SafeSQLString added in v0.2.0

func SafeSQLString(s string) string

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

func SanitizeString(badStringsList []string, stringToClean string) string

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 SelectJsonFields(obj any, fieldsToSelect []string) (string, error)

func SetErrorLogger added in v0.3.1

func SetErrorLogger(logger *zap.SugaredLogger)

SetErrorLogger allows injecting a custom logger for ErrorPlus instances.

func SetLoglevel

func SetLoglevel(loglevel string, instanceId string, log2file bool, logfilePath string)

func Sort added in v0.2.0

func Sort[T any](slice []T, less func(T, T) bool)

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 StrPtr added in v0.2.0

func StrPtr(s string) *string

StrPtr returns a pointer to the given string

func StringSliceContains

func StringSliceContains(s []string, e string) bool

@Summary StringSliceContains checks if a string slice contains a string.

func StringSliceIndexOf

func StringSliceIndexOf(s []string, e string) int

func StringSliceRemoveIndex

func StringSliceRemoveIndex(s []string, index int) []string

func StringSliceRemoveString

func StringSliceRemoveString(max int, sourceSlice []string, stringToRemove string) []string

func StringSlicesHaveSameContent

func StringSlicesHaveSameContent(source []string, compare []string) bool

func SyslogTimeEncoder

func SyslogTimeEncoder(t time.Time, enc zapcore.PrimitiveArrayEncoder)

func TimeFromJSTimestamp added in v0.1.4

func TimeFromJSTimestamp(timestamp int64) time.Time

this is just to remember that javascript Date.now() converts like this

func TimeFromUnixTimestamp

func TimeFromUnixTimestamp(timestamp int64) time.Time

func TimeToJSTimestamp added in v0.1.4

func TimeToJSTimestamp(t time.Time) int64

this is just to remember that javascript Date.now() converts like this

func Uint32Ptr added in v0.2.0

func Uint32Ptr(u uint32) *uint32

Uint32Ptr returns a pointer to the given uint32

func Uint64Ptr added in v0.2.0

func Uint64Ptr(u uint64) *uint64

Uint64Ptr returns a pointer to the given uint64

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 CommandLineParameters struct {
	SeedDb     *bool
	EnvFile    *string
	ConfigFile *string
}

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

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

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

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

func NewBadRequestError(msg string, err error) *ErrorPlus

NewBadRequestError creates a new ErrorPlus representing a 400 Bad Request error.

func NewErrorPlus added in v0.3.1

func NewErrorPlus(err error, msg string, code int) *ErrorPlus

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

func NewInternalError(msg string, err error) *ErrorPlus

NewInternalError creates a new ErrorPlus representing a 500 Internal Server Error.

func NewNotFoundError added in v0.3.1

func NewNotFoundError(msg string, err error) *ErrorPlus

NewNotFoundError creates a new ErrorPlus representing a 404 Not Found error.

func NewUnauthorizedError added in v0.3.1

func NewUnauthorizedError(msg string, err error) *ErrorPlus

NewUnauthorizedError creates a new ErrorPlus representing a 401 Unauthorized error.

func (*ErrorPlus) As added in v0.3.1

func (e *ErrorPlus) As(target interface{}) bool

As attempts to map the ErrorPlus to a target error type, useful for type assertion.

func (*ErrorPlus) Code added in v0.3.1

func (e *ErrorPlus) Code() int

Code returns the error code associated with the ErrorPlus.

func (*ErrorPlus) CodeStr added in v0.3.3

func (e *ErrorPlus) CodeStr() string

CodeStr returns the error code as a string.

func (*ErrorPlus) Context added in v0.3.1

func (e *ErrorPlus) Context() map[string]interface{}

Context returns the additional context associated with the ErrorPlus.

func (*ErrorPlus) ContextStr added in v0.3.3

func (e *ErrorPlus) ContextStr() string

ErrorStr returns the error message as a string.

func (*ErrorPlus) Error added in v0.3.1

func (e *ErrorPlus) Error() string

Error implements the error interface, returning the error message including context and original error.

func (*ErrorPlus) Format added in v0.3.1

func (e *ErrorPlus) Format(f fmt.State, c rune)

Format implements the fmt.Formatter interface for custom formatting.

func (*ErrorPlus) Is added in v0.3.1

func (e *ErrorPlus) Is(target error) bool

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

func (e *ErrorPlus) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface, allowing custom JSON serialization.

func (*ErrorPlus) Msg added in v0.3.3

func (e *ErrorPlus) Msg() string

ErrorMsg returns the error message without the original error.

func (*ErrorPlus) StackTrace added in v0.3.1

func (e *ErrorPlus) StackTrace() []string

StackTrace returns the stack trace associated with the error.

func (*ErrorPlus) Timestamp added in v0.3.1

func (e *ErrorPlus) Timestamp() time.Time

Timestamp returns the time when the error was created.

func (*ErrorPlus) Unwrap added in v0.3.1

func (e *ErrorPlus) Unwrap() error

Unwrap returns the underlying original error, allowing access to the original error for further handling.

func (*ErrorPlus) WithCode added in v0.3.1

func (e *ErrorPlus) WithCode(code int) *ErrorPlus

WithCode returns a new ErrorPlus with the provided code, preserving immutability.

func (*ErrorPlus) WithContext added in v0.3.1

func (e *ErrorPlus) WithContext(key string, value interface{}) *ErrorPlus

WithContext returns a new ErrorPlus with the additional context, preserving immutability.

func (*ErrorPlus) WithMsg added in v0.3.1

func (e *ErrorPlus) WithMsg(msg string) *ErrorPlus

WithMsg returns a new ErrorPlus with the provided message, preserving immutability.

func (*ErrorPlus) WithValues added in v0.3.1

func (e *ErrorPlus) WithValues(msg string, code int) *ErrorPlus

WithValues returns a new ErrorPlus with the provided message and code, preserving immutability.

type EventData added in v0.3.4

type EventData struct {
	EventID EventID
	Data    map[string]interface{}
}

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 EventID added in v0.2.0

type EventID string

EventID is a unique identifier for an event.

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

type SMCondition func(context map[string]interface{}) bool

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

func (s *Set[T]) Add(items ...T) *Set[T]

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

func (s *Set[T]) Contains(item T) bool

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

func (s *Set[T]) Difference(other *Set[T]) *Set[T]

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

func (s *Set[T]) Intersection(other *Set[T]) *Set[T]

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

func (s *Set[T]) Remove(items ...T) *Set[T]

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

func (s *Set[T]) Size() int

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

func (s *Set[T]) String() string

String returns a string representation of the set

Returns:

  • string: a string representation of the set

func (*Set[T]) ToSlice added in v0.2.0

func (s *Set[T]) ToSlice() []T

ToSlice returns a slice of all items in the set

Returns:

  • []T: a slice containing all items in the set

func (*Set[T]) Union added in v0.2.0

func (s *Set[T]) Union(other *Set[T]) *Set[T]

Union returns a new set that is the union of this set and another set

Parameters:

  • other: the other set to union with

Returns:

  • *Set[T]: a new Set containing the union of both sets

type State added in v0.2.0

type State struct {
	ID           StateID
	Name         string
	EntryActions []SMAction
	ExitActions  []SMAction
}

State represents a state in the state machine.

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

func NewStatesMan(name string) *StatesMan

NewStatesMan creates a new StatesMan instance.

func (*StatesMan) AddPostHook added in v0.2.0

func (sm *StatesMan) AddPostHook(hook SMAction)

AddPostHook adds a post-transition hook.

func (*StatesMan) AddPreHook added in v0.2.0

func (sm *StatesMan) AddPreHook(hook SMAction)

AddPreHook adds a pre-transition hook.

func (*StatesMan) AddState added in v0.2.0

func (sm *StatesMan) AddState(id StateID, name string, entryActions, exitActions []SMAction)

AddState adds a new state to the state machine.

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) Export added in v0.2.0

func (sm *StatesMan) Export() (string, error)

Export exports the state machine configuration to JSON.

func (*StatesMan) GenerateDOT added in v0.2.0

func (sm *StatesMan) GenerateDOT() string

GenerateDOT generates a DOT representation of the state machine for visualization.

func (*StatesMan) GetCurrentState added in v0.2.0

func (sm *StatesMan) GetCurrentState() StateID

GetCurrentState returns the current state of the state machine.

func (*StatesMan) Import added in v0.2.0

func (sm *StatesMan) Import(jsonStr string) error

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

func (sm *StatesMan) SetInitialState(id StateID) error

SetInitialState sets the initial state of the state machine.

func (*StatesMan) TriggerEvent added in v0.2.0

func (sm *StatesMan) TriggerEvent(event EventID, data map[string]interface{})

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

func (t *Trie) AutoComplete(prefix string, limit int) []string

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

func (t *Trie) BulkInsert(words []string)

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

func (t *Trie) Insert(word string)

Insert adds a word to the Trie.

Example:

trie := NewTrie()
trie.Insert("apple")

func (*Trie) InsertWithValue added in v0.2.0

func (t *Trie) InsertWithValue(word string, value interface{})

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

func (t *Trie) LongestCommonPrefix() string

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

func (t *Trie) Search(word string) bool

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

func (t *Trie) StartsWith(prefix string) bool

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

func (t *Trie) WildcardSearch(pattern string) []string

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

Jump to

Keyboard shortcuts

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