utils

package module
v1.13.11 Latest Latest
Warning

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

Go to latest
Published: Jan 31, 2024 License: MIT Imports: 36 Imported by: 2

README

Utilities for the Go

Utilities for the Golang package. The utils package is a generic package that provides utility functions and structures that can be used across different parts of a program. The package contains several functions and structures that can be used to simplify common tasks.

Installation

go get github.com/dollarsignteam/go-utils

Usage

PointerOf returns a pointer to the input value. For example:

x := 42
ptr := PointerOf(x)
fmt.Println(*ptr) // Output: 42

PackageName returns the name of the package that calls it. For example:

fmt.Println(PackageName()) // Output: utils

UniqueOf removes duplicates from a slice of any type and returns a new slice containing only the unique elements. For example:

input := []int{1, 2, 3, 2, 1}
unique := UniqueOf(input)
fmt.Println(unique) // Output: [1 2 3]

ValueOf takes a pointer to a value of any type and returns the value. For example:

x := 42
ptr := &x
val := ValueOf(ptr)
fmt.Println(val) // Output: 42

IsArrayOrSlice takes a value of any type and returns a boolean indicating if it is a slice or an array. For example:

arr := [3]int{1, 2, 3}
slice := []int{1, 2, 3}
fmt.Println(IsArrayOrSlice(arr)) // Output: true
fmt.Println(IsArrayOrSlice(slice)) // Output: true
fmt.Println(IsArrayOrSlice(x)) // Output: false

BoolToInt converts a boolean value to an integer (1 for true, 0 for false). For example:

fmt.Println(BoolToInt(true)) // Output: 1
fmt.Println(BoolToInt(false)) // Output: 0

IntToBool converts an integer value to a boolean (true for non-zero values, false for zero). For example:

fmt.Println(IntToBool(1)) // Output: true
fmt.Println(IntToBool(0)) // Output: false

For more information, check out the 📚 documentation.

Contributing

Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.

Author

Dollarsign

License

Licensed under the MIT License - see the LICENSE file for details.

Documentation

Index

Examples

Constants

View Source
const (
	ErrCodeSomethingWentWrong = "SOMETHING_WENT_WRONG"
	ErrCodeBadRequest         = "BAD_REQUEST"
	ErrCodeUnauthorized       = "UNAUTHORIZED"
)

Error code constants

View Source
const (
	ErrMessageSomethingWentWrong = "Something went wrong"
	ErrMessageBadRequest         = "Bad request"
	ErrMessageUnauthorized       = "Unauthorized"
)

Error message constants

View Source
const (
	DefaultRedisSessionKey = "session"
	DefaultRedisUserKey    = "user"
)

Default keys for storing session and user data in Redis.

View Source
const (
	MySQLDateTimeLayout = "2006-01-02 15:04:05"
	MySQLDateLayout     = "2006-01-02"
	MySQLTimeLayout     = "15:04:05"
)
View Source
const (
	AsiaBangkokLocation  = "Asia/Bangkok"
	AsiaHongKongLocation = "Asia/Hong_Kong"
)

Variables

View Source
var (
	ErrSessionNotFound = errors.New("session not found") // Error for when session is not found.
	ErrSessionInvalid  = errors.New("invalid session")   // Error for when session is invalid.
)
View Source
var (
	BangkokTimeLocation, _  = time.LoadLocation(AsiaBangkokLocation)
	HongKongTimeLocation, _ = time.LoadLocation(AsiaHongKongLocation)
)

time.Location instances

View Source
var RegExpNumberString = regexp.MustCompile(`^-?([1-9]{1}\d{0,2}(\,\d{3})*(\.\d+)?|[1-9]{1}\d*(\.\d+)?|0(\.\d+)?|(\.\d+)?)$`)

RegExpNumberString a regular expression to match number strings with optional thousands separators and decimal portions.

View Source
var Validate = validator.New()

Validate a new instance of the validator library.

Functions

func BoolToInt added in v1.3.0

func BoolToInt(b bool) int

BoolToInt converts a boolean value to an integer (1 for true, 0 for false).

Example
b := true
i := utils.BoolToInt(b)
fmt.Println(i)
Output:

1

func DifferenceOf added in v1.10.0

func DifferenceOf[T comparable](input ...[]T) []T

DifferenceOf returns a slice containing all unique elements across all input slices, The order of elements in the resulting slice is not guaranteed

func Filter added in v1.11.0

func Filter[T any](s []T, f func(T) bool) []T

Filter applies a function to each element of a slice and returns a new slice with the elements that passed the test

s is the slice to be filtered
f is the function to be applied to each element of the slice

func GetJSONTagName added in v1.4.0

func GetJSONTagName(field reflect.StructField) string

GetJSONTagName returns the name of the JSON tag associated with a given reflect.StructField.

func IntToBool added in v1.3.0

func IntToBool(i int) bool

IntToBool converts an integer value to a boolean (true for non-zero values, false for zero).

Example
i := 0
b := utils.IntToBool(i)
fmt.Println(b)
Output:

false

func IntersectionOf added in v1.10.0

func IntersectionOf[T comparable](input ...[]T) []T

IntersectionOf returns the intersection of all input slices, preserving the order of the first occurrence of each shared element.

func IsArrayOrSlice

func IsArrayOrSlice(i any) bool

IsArrayOrSlice takes a value of any type and returns a boolean indicating if it is a slice or an array.

Example
s := []int{1, 2, 3, 4, 5}
fmt.Println(utils.IsArrayOrSlice(s))
Output:

true

func IsCommonError added in v1.4.0

func IsCommonError(err error) bool

IsCommonError returns true if the given error is a CommonError.

func IsValidationError added in v1.4.0

func IsValidationError(err error) bool

IsValidationError returns true if the given error is a IsValidationError.

func Map added in v1.11.0

func Map[T any](s []T, f func(T) T) []T

Map applies a function to each element of a slice and returns a new slice

s is the slice to be mapped
f is the function to be applied to each element of the slice

func Max

func Max[T constraints.Ordered](x, y T) T

Max returns the maximum of two ordered values x and y.

Example
fmt.Println(utils.Max(4, 9))
fmt.Println(utils.Max(9, 4))
Output:

9
9

func MaxOf

func MaxOf[T constraints.Ordered](s []T) T

MaxOf returns the maximum value in the ordered slice s. Returns the zero value of T if s is empty.

Example
fmt.Println(utils.MaxOf([]int{5, 2, 8, 1}))
fmt.Println(utils.MaxOf([]int{9, 10, 20}))
fmt.Println(utils.MaxOf([]int{}))
Output:

8
20
0

func Min

func Min[T constraints.Ordered](x, y T) T

Min returns the minimum of two ordered values x and y.

Example
fmt.Println(utils.Min(4, 9))
fmt.Println(utils.Min(9, 4))
Output:

4
4

func MinOf

func MinOf[T constraints.Ordered](s []T) T

MinOf returns the minimum value in the ordered slice s. Returns the zero value of T if s is empty.

Example
fmt.Println(utils.MinOf([]int{5, 2, 8, 1}))
fmt.Println(utils.MinOf([]int{9, 10, 20}))
fmt.Println(utils.MinOf([]int{}))
Output:

1
9
0

func PackageName

func PackageName() string

PackageName returns the name of the package that calls it.

Example
fmt.Println(utils.PackageName())
Output:

go-utils_test

func ParseFloat64

func ParseFloat64(s string) (float64, error)

ParseFloat64 parses a string s as a float64 value.

Example
f, err := utils.ParseFloat64("3.14")
if err == nil {
	fmt.Println(f)
}
Output:

3.14

func PointerOf

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

PointerOf returns a pointer to the input value

Example
x := 20
p := utils.PointerOf(x)
fmt.Println(*p)
Output:

20

func RandomFloat64

func RandomFloat64(min, max float64) float64

RandomFloat64 generates a random float64 value between min and max.

Example
fmt.Println(utils.RandomFloat64(10.5, 10.5))
Output:

10.5

func RandomInt64

func RandomInt64(min, max int64) int64

RandomInt64 generates a random int64 value between min and max.

Example
fmt.Println(utils.RandomInt64(10, 10))
Output:

10

func Reduce added in v1.11.0

func Reduce[T any](s []T, f func(prev T, curr T) T, initial T) T

Reduce applies a function to each element of a slice and return the accumulated result

s is the slice to be reduced
f is the function to be applied to each element of the slice
initial is the initial value of the accumulator

func SimpleSort added in v1.11.0

func SimpleSort[T constraints.Ordered](s []T) []T

SimpleSort sorts a slice of ordered elements using efficient merge sort

Note: this function is not generic, it only works with ordered elements
s is the slice to be sorted
returns a new slice with the elements sorted

func SortFunc added in v1.11.0

func SortFunc[T any](s []T, f func(T, T) bool) []T

SortFunc sorts a slice of elements using a function to compare them

func UnionOf added in v1.10.0

func UnionOf[T any](input ...[]T) []T

UnionOf returns the union of all input slices, preserving the order of the first occurrence of each unique element.

func UniqueOf

func UniqueOf[T any](input []T) []T

UniqueOf removes duplicates from a slice of any type and returns a new slice containing only the unique elements.

Example
s := []int{1, 2, 2, 3, 4, 4, 5, 5, 5}
u := utils.UniqueOf(s)
fmt.Println(u)
Output:

[1 2 3 4 5]

func ValidateNumberString

func ValidateNumberString(fl validator.FieldLevel) bool

ValidateNumberString validates a given number string by checking whether it matches the RegExpNumberString regular expression pattern.

func ValidateStruct added in v1.4.0

func ValidateStruct(s any) error

ValidateStruct validates the fields of a struct using the validator library. if validation fails, it calls the ParseValidationError() function to convert ValidationErrors into a ValidationError error type.

func ValueOf

func ValueOf[T any](ptr *T) T

ValueOf takes a pointer to a value of any type and returns the value.

Example
x := 20
p := utils.PointerOf(x)
v := utils.ValueOf(p)
fmt.Println(v)
Output:

20

Types

type AMQPClient added in v1.12.0

type AMQPClient struct {
	Connection      *amqp.Conn
	SenderSession   *amqp.Session
	ReceiverSession *amqp.Session
	SenderList      []*amqp.Sender
	ReceiverList    []*amqp.Receiver
	// contains filtered or unexported fields
}

AMQPClient is a wrapper around the AMQP client

func (*AMQPClient) Close added in v1.12.0

func (client *AMQPClient) Close()

Close closes all senders, receivers, sender session, receiver session and the connection of the AMQPClient

func (*AMQPClient) IsErrorClosed added in v1.12.0

func (client *AMQPClient) IsErrorClosed(err error) (error, bool)

IsErrorClosed checks if the given error is a closed error

func (*AMQPClient) NewPublisher added in v1.12.0

func (client *AMQPClient) NewPublisher(topic string) (*amqp.Sender, error)

NewPublisher creates a new publisher for the given topic

func (*AMQPClient) NewReceiver added in v1.12.0

func (client *AMQPClient) NewReceiver(queue string) (*amqp.Receiver, error)

NewReceiver creates a new receiver for the given queue

func (*AMQPClient) NewReceiverList added in v1.12.0

func (client *AMQPClient) NewReceiverList(queue string, count int) ([]*amqp.Receiver, error)

NewSenderList creates a list of senders for the given queue

func (*AMQPClient) NewSender added in v1.12.0

func (client *AMQPClient) NewSender(queue string) (*amqp.Sender, error)

NewSender creates a new sender for the given queue

func (*AMQPClient) NewSubscriber added in v1.12.0

func (client *AMQPClient) NewSubscriber(topic string) (*amqp.Receiver, error)

NewSubscriber creates a new subscriber for the given topic

func (*AMQPClient) Publish added in v1.12.0

func (client *AMQPClient) Publish(publisher *amqp.Sender, message *amqp.Message) error

Publish publishes the given message to the given publisher

func (*AMQPClient) Received added in v1.12.0

func (client *AMQPClient) Received(receiver *amqp.Receiver, messageHandlerFunc AMQPMessageHandlerFunc)

Received receives messages from the given receiver and handles them with the provided message handler function. If the message handler function returns false, the loop stops. If the message handler function returns an error, the message is rejected; otherwise, it is accepted for further processing.

func (*AMQPClient) ReceivedList added in v1.12.0

func (client *AMQPClient) ReceivedList(receiverList []*amqp.Receiver, messageHandlerFunc AMQPMessageHandlerFunc)

ReceivedList receives messages from the given list of receivers and handles them with the provided message handler function.

func (*AMQPClient) Send added in v1.12.0

func (client *AMQPClient) Send(sender *amqp.Sender, message *amqp.Message, persistent bool) error

Send sends the given message to the given sender with the specified persistence flag. If the persistence flag is set to true, the message will be saved to disk for durability. If the message's header is nil, it will be initialized with a new amqp.MessageHeader. The Durable field of the message header will be updated to reflect the persistence flag. Note: Setting the persistence flag to true might result in slower performance.

type AMQPConfig added in v1.12.0

type AMQPConfig struct {
	URL string
}

AMQPConfig is the configuration for the AMQP client

type AMQPMessageHandler added in v1.12.0

type AMQPMessageHandler struct {
	IsClosed bool
	Rejected bool
}

AMQPMessageHandler is the handler for the received message

type AMQPMessageHandlerFunc added in v1.12.0

type AMQPMessageHandlerFunc func(message *amqp.Message, err error) *AMQPMessageHandler

AMQPMessageHandlerFunc is the function to handle the received message

type AMQPUtil added in v1.12.0

type AMQPUtil struct{}

AMQPUtil is a utility for AMQP

var AMQP AMQPUtil

AMQP utility instance

func (AMQPUtil) GetSubject added in v1.12.0

func (AMQPUtil) GetSubject(message *amqp.Message) string

GetSubject gets the subject of the given message

func (AMQPUtil) New added in v1.12.0

func (AMQPUtil) New(config AMQPConfig) (*AMQPClient, error)

New creates a new AMQP client

type Backend added in v1.13.3

type Backend struct {
	Name   string
	Weight int
}

func LoadBalancedByWeight added in v1.13.3

func LoadBalancedByWeight(backends []Backend) *Backend

LoadBalancedByWeight selects a backend based on their weight.

type CommonError added in v1.4.0

type CommonError struct {
	StatusCode    int    `json:"statusCode"`   // HTTP status code
	ErrorCode     string `json:"errorCode"`    // Specific error code
	ErrorInstance error  `json:"errorMessage"` // The actual error instance
}

CommonError type for generic errors with status codes and error codes

func NewCommonErrorBadRequest added in v1.5.2

func NewCommonErrorBadRequest(err error) CommonError

NewCommonErrorBadRequest creates a new CommonError instance with `Bad request` ErrorInstance field.

func NewCommonErrorSomethingWentWrong added in v1.4.0

func NewCommonErrorSomethingWentWrong(err error) CommonError

NewCommonErrorSomethingWentWrong creates a new CommonError instance with `Something went wrong` ErrorInstance field.

func ParseCommonError added in v1.4.0

func ParseCommonError(err error) CommonError

ParseCommonError checks if the given error is a CommonError instance and returns it. If not, it creates a new CommonError instance using NewCommonErrorSomethingWentWrong.

func (CommonError) Error added in v1.4.0

func (e CommonError) Error() string

Error function for CommonError to return the error message

func (CommonError) MarshalJSON added in v1.4.0

func (e CommonError) MarshalJSON() ([]byte, error)

MarshalJSON function for CommonError to marshal the error as JSON

func (*CommonError) UnmarshalJSON added in v1.4.0

func (e *CommonError) UnmarshalJSON(data []byte) error

UnmarshalJSON function for CommonError to unmarshal the error from JSON

type EMVCoQRInfo added in v1.13.1

type EMVCoQRInfo struct {
	Format          string
	MerchantAccount string
	Amount          string
	PhoneNumber     string
	CountryCode     string
	Crc             string
	CurrencyISO4217 string
	BillerID        string
	Ref1            string
	Ref2            string
	Ref3            string
}

EMVCoQRInfo for QR string

type EchoBinderWithValidation added in v1.5.0

type EchoBinderWithValidation struct {
	echo.DefaultBinder
}

EchoBinderWithValidation is a struct that implements the echo.Binder interface with added validation functionality.

var EchoBinder EchoBinderWithValidation

EchoBinder utility instance

func (*EchoBinderWithValidation) Bind added in v1.5.0

func (b *EchoBinderWithValidation) Bind(i any, c echo.Context) error

Bind binds request data, validates it using ValidateStruct(), and returns an error if binding or validation fails.

func (*EchoBinderWithValidation) BindAll added in v1.13.10

func (b *EchoBinderWithValidation) BindAll(i any, c echo.Context) error

BindAll binds all request data, validates it using ValidateStruct(),

func (*EchoBinderWithValidation) BindBody added in v1.6.2

func (b *EchoBinderWithValidation) BindBody(c echo.Context, i any) error

BindBody binds body data, validates it using ValidateStruct(), and returns an error if binding or validation fails.

func (*EchoBinderWithValidation) BindHeaders added in v1.6.2

func (b *EchoBinderWithValidation) BindHeaders(c echo.Context, i any) error

BindHeaders binds headers data, validates it using ValidateStruct(), and returns an error if binding or validation fails.

func (*EchoBinderWithValidation) BindPathParams added in v1.6.2

func (b *EchoBinderWithValidation) BindPathParams(c echo.Context, i any) error

BindPathParams binds path params, validates them using ValidateStruct(), and returns an error if binding or validation fails.

func (*EchoBinderWithValidation) BindQueryParams added in v1.6.2

func (b *EchoBinderWithValidation) BindQueryParams(c echo.Context, i any) error

BindQueryParams binds query params, validates them using ValidateStruct(), and returns an error if binding or validation fails.

type EchoJWTConfig added in v1.6.0

type EchoJWTConfig struct {
	SigningKey        string                                       // The signing key used to sign JWT tokens
	ExpiresTTL        time.Duration                                // The duration until which the token should be valid
	BeforeSuccessFunc func(token *jwt.Token, c echo.Context) error // A callback function to execute before a successful authentication
}

EchoJWTConfig is the configuration struct for EchoJWTUtil

type EchoJWTUtil added in v1.6.0

type EchoJWTUtil struct {
	Config *EchoJWTConfig // The configuration for EchoJWTUtil
	// contains filtered or unexported fields
}

EchoJWTUtil is a utility struct that provides methods for working with JWT tokens in the context of the Echo web framework

var EchoJWT EchoJWTUtil

EchoJWT utility instance

func (EchoJWTUtil) CreateToken added in v1.6.0

func (eJWT EchoJWTUtil) CreateToken(claims jwt.RegisteredClaims) JWTToken

CreateToken creates and returns a new JWTToken

func (EchoJWTUtil) GetClaims added in v1.6.0

func (eJWT EchoJWTUtil) GetClaims(token *jwt.Token) (*jwt.RegisteredClaims, error)

GetClaims retrieves and validates JWT claims. It takes a JWT token and returns the converted claims

func (EchoJWTUtil) JWTAuth added in v1.6.0

func (eJWT EchoJWTUtil) JWTAuth() echo.MiddlewareFunc

JWTAuth returns a new instance of the echo-jwt middleware, configured with the current EchoJWTConfig object

func (EchoJWTUtil) KeyFunc added in v1.6.0

func (eJWT EchoJWTUtil) KeyFunc(token *jwt.Token) (any, error)

KeyFunc is a helper function used by ParseToken to extract the signing key from the EchoJWTConfig object

func (EchoJWTUtil) New added in v1.6.0

func (EchoJWTUtil) New(config *EchoJWTConfig) *EchoJWTUtil

New creates and returns a new instance of EchoJWTUtil

func (EchoJWTUtil) ParseToken added in v1.6.0

func (eJWT EchoJWTUtil) ParseToken(signedToken string) (*jwt.Token, error)

ParseToken is a helper function used to parse and validate JWT tokens using the echo-jwt library

func (EchoJWTUtil) ParseTokenFunc added in v1.6.0

func (eJWT EchoJWTUtil) ParseTokenFunc(c echo.Context, auth string) (any, error)

ParseTokenFunc is a callback function used to parse and validate JWT tokens within the context of the echo-jwt middleware

func (*EchoJWTUtil) SetSkipper added in v1.11.1

func (eJWT *EchoJWTUtil) SetSkipper(skipper middleware.Skipper)

SetSkipper sets the middleware skipper function for the EchoJWTUtil instance.

type EchoUtil added in v1.5.0

type EchoUtil struct{}

EchoUtil is a utility struct for working with Echo instances

var Echo EchoUtil

Echo utility instance

func (EchoUtil) DefaultRootHandler added in v1.5.0

func (EchoUtil) DefaultRootHandler(c echo.Context) error

DefaultRootHandler handles requests to the root endpoint

func (EchoUtil) New added in v1.5.0

func (EchoUtil) New() *echo.Echo

New creates a new instance of the Echo framework

func (EchoUtil) NoContentHandler added in v1.5.1

func (EchoUtil) NoContentHandler(c echo.Context) error

NoContentHandler handles return no content endpoint

type EchoValidator added in v1.5.0

type EchoValidator struct{}

EchoValidator is a struct that implements the echo.Validator interface.

func (EchoValidator) Validate added in v1.5.0

func (EchoValidator) Validate(i any) error

Validate is a method that validates the given struct using the ValidateStruct function and returns an error if validation fails.

type ErrorResponse added in v1.4.1

type ErrorResponse struct {
	StatusCode       int                     `json:"statusCode" example:"500"`                                     // HTTP status code
	ErrorCode        string                  `json:"errorCode,omitempty" example:"SOMETHING_WENT_WRONG"`           // Specific error code
	ErrorMessage     string                  `json:"errorMessage,omitempty" example:"Oops, something went wrong!"` // Custom error message
	ErrorDescription string                  `json:"errorDescription,omitempty" example:"Something went wrong"`    // The actual error message
	ErrorValidation  []ValidationErrorDetail `json:"errorValidation,omitempty"`                                    // List of validation errors
}

ErrorResponse represents an error response with error code, message, description, and validation errors

func ParseErrorResponse added in v1.5.1

func ParseErrorResponse(err error) ErrorResponse

ParseErrorResponse converts an error into a ErrorResponse. If the input error is a ErrorResponse, it's returned as is.

type ImageUtil added in v1.10.2

type ImageUtil struct{}

ImageUtil is a utility struct for image related functions

var Image ImageUtil

Image utility instance

func (ImageUtil) IsImage added in v1.10.2

func (ImageUtil) IsImage(fh *multipart.FileHeader) bool

IsImage checks if the file is an image

func (ImageUtil) IsImageContentType added in v1.11.0

func (ImageUtil) IsImageContentType(fh *multipart.FileHeader) bool

IsImageContentType checks if the content type is an image

type JWTToken added in v1.6.0

type JWTToken struct {
	SignedString string               // The signed token as a string
	Claims       jwt.RegisteredClaims // The claims included in the token
}

JWTToken is a helper struct for returning signed JWT tokens

type JsonUtil added in v1.10.2

type JsonUtil struct{}

JsonUtil is a struct with methods for parsing and validating JSON data.

var JSON JsonUtil

JSON utility instance

func (JsonUtil) Parse added in v1.10.2

func (JsonUtil) Parse(data string, result any) error

Parse parses JSON data into the given result struct.

func (JsonUtil) ParseAndValidate added in v1.10.2

func (JsonUtil) ParseAndValidate(data string, result any) error

ParseAndValidate parses and validates JSON data into the given result struct. If the result is an array or slice, it is validated as a list of items.

type RedisClient added in v1.8.0

type RedisClient struct {
	*redis.Client
}

RedisClient is a wrapper around go-redis Client type

func (*RedisClient) GetStruct added in v1.8.0

func (r *RedisClient) GetStruct(key string, result any) error

GetStruct retrieves the value of a key as a JSON-encoded struct and unmarshal it into a provided result variable

func (*RedisClient) JSONGet added in v1.8.0

func (r *RedisClient) JSONGet(key string, result any) error

JSONGet is a convenience wrapper around GetStruct

func (*RedisClient) JSONSet added in v1.8.0

func (r *RedisClient) JSONSet(key string, value any, expiration time.Duration) error

JSONSet is a convenience wrapper around SetStruct

func (*RedisClient) SetNXStruct added in v1.8.0

func (r *RedisClient) SetNXStruct(key string, value any, expiration time.Duration) (bool, error)

SetNXStruct sets the value for a key in Redis if the key does not already exist The value is marshalled to JSON, and an optional expiration time can be set Returns a boolean indicating whether the key was set, and an error (if any)

func (*RedisClient) SetStruct added in v1.8.0

func (r *RedisClient) SetStruct(key string, value any, expiration time.Duration) error

SetStruct sets the value for a key in Redis The value is marshalled to JSON, and an optional expiration time can be set

type RedisConfig added in v1.8.0

type RedisConfig struct {
	URL string
}

RedisConfig specifies configuration options for connecting to a Redis server

type RedisUtil added in v1.8.0

type RedisUtil struct{}

RedisUtil is a utility struct for working with Redis

var Redis RedisUtil

Redis utility instance

func (RedisUtil) New added in v1.8.0

func (RedisUtil) New(config RedisConfig) (*RedisClient, error)

New creates a new Redis client based on the provided RedisConfig

func (RedisUtil) NewSessionHandler added in v1.9.0

func (RedisUtil) NewSessionHandler(config SessionRedisConfig) SessionHandler

NewSessionHandler creates a new Redis session handler using the provided configuration.

type Result

type Result struct {
	List any `validate:"dive"`
}

Result struct definition for a Result object.

type Session added in v1.9.0

type Session struct {
	Meta SessionMeta `json:"meta"`           // Metadata associated with the session.
	Data any         `json:"data,omitempty"` // Optional data associated with the session.
}

Session represents a session with associated metadata and data.

func (Session) Scan added in v1.9.1

func (session Session) Scan(dest any) error

Scan reads session data and decodes it into a Go value pointed to by dest using JSON parsing and validation.

type SessionHandler added in v1.9.0

type SessionHandler interface {
	Set(session Session, expiresAt int64) error
	Get(meta SessionMeta) (Session, error)
	ListByUserID(userId int64) ([]Session, error)
	ListByGroupID(groupId string) ([]Session, error)
	Exists(meta SessionMeta) (bool, error)
	Count(uniqueByUser bool) (int, error)
	CountByUserID(userId int64, uniqueByUser bool) (int, error)
	CountByGroupID(groupId string, uniqueByUser bool) (int, error)
	Delete(meta SessionMeta) error
	DeleteByUserID(userId int64) error
	DeleteByGroupID(groupId string) error
	DeleteAll() error
}

SessionHandler represents an interface for managing sessions.

type SessionMeta added in v1.9.1

type SessionMeta struct {
	ID      string `json:"sid"`           // ID of the session.
	UserID  int64  `json:"uid"`           // ID of the user associated with the session.
	GroupID string `json:"gid,omitempty"` // Optional ID of the group associated with the session.
}

SessionMeta represents metadata associated with a session.

type SessionRedisConfig added in v1.9.0

type SessionRedisConfig struct {
	SessionKey             string       // key for storing session data in Redis
	UserKey                string       // key for storing user-session mappings in Redis
	MultipleSessionPerUser bool         // whether to allow multiple sessions per user
	Client                 *RedisClient // Redis client instance to use for accessing the server
}

SessionRedisConfig is used to configure session data stored in Redis.

type SessionRedisHandler added in v1.9.0

type SessionRedisHandler struct {
	// contains filtered or unexported fields
}

SessionRedisHandler is used to handle session information stored in Redis.

func (*SessionRedisHandler) Count added in v1.9.0

func (h *SessionRedisHandler) Count(uniqueByUser bool) (int, error)

Count returns the total number of sessions stored in Redis with option to count only unique sessions.

func (*SessionRedisHandler) CountByGroupID added in v1.9.0

func (h *SessionRedisHandler) CountByGroupID(groupId string, uniqueByUser bool) (int, error)

CountByGroupID counts the number of sessions stored in Redis for a specific group ID.

func (*SessionRedisHandler) CountByUserID added in v1.9.0

func (h *SessionRedisHandler) CountByUserID(userId int64, uniqueByUser bool) (int, error)

CountByUserID counts the number of sessions stored in Redis for a specific user ID, with option to count only unique sessions.

func (*SessionRedisHandler) Delete added in v1.9.0

func (h *SessionRedisHandler) Delete(meta SessionMeta) error

Delete deletes a session from Redis based on its metadata.

func (*SessionRedisHandler) DeleteAll added in v1.9.0

func (h *SessionRedisHandler) DeleteAll() error

DeleteAll deletes all sessions stored in Redis.

func (*SessionRedisHandler) DeleteByGroupID added in v1.9.0

func (h *SessionRedisHandler) DeleteByGroupID(groupId string) error

DeleteByGroupID deletes all sessions corresponding to a given group ID.

func (*SessionRedisHandler) DeleteByUserID added in v1.9.0

func (h *SessionRedisHandler) DeleteByUserID(userId int64) error

DeleteByUserID deletes all sessions corresponding to a given user ID.

func (*SessionRedisHandler) Exists added in v1.9.0

func (h *SessionRedisHandler) Exists(meta SessionMeta) (bool, error)

Exists checks if session data corresponding to the given SessionMeta exists in Redis.

func (*SessionRedisHandler) Get added in v1.9.0

func (h *SessionRedisHandler) Get(meta SessionMeta) (Session, error)

Get retrieves session data from Redis using the provided metadata.

func (*SessionRedisHandler) ListByGroupID added in v1.9.0

func (h *SessionRedisHandler) ListByGroupID(groupId string) ([]Session, error)

ListByGroupID returns a list of sessions associated with the given group ID. If "*" is passed as the groupId parameter, returns an empty slice and nil error.

func (*SessionRedisHandler) ListByUserID added in v1.9.0

func (h *SessionRedisHandler) ListByUserID(userId int64) ([]Session, error)

ListByUserID returns a list of sessions associated with the given user ID.

func (*SessionRedisHandler) Set added in v1.9.0

func (h *SessionRedisHandler) Set(s Session, expiresAt int64) error

Set saves session data to Redis and sets an expiration time.

type StringUtil

type StringUtil struct{}

StringUtil provides utility functions for manipulating strings

var String StringUtil

String utility instance

func (StringUtil) AESDecrypt added in v1.13.6

func (StringUtil) AESDecrypt(key, cipherText string) (string, error)

Decrypt decrypts the given cipherText using AES decryption with the provided key.

func (StringUtil) AESEncrypt added in v1.13.6

func (StringUtil) AESEncrypt(key, plaintext string) (string, error)

Encrypt encrypts the given plaintext using AES encryption with the provided key.

func (StringUtil) HashCrc32 added in v1.11.2

func (StringUtil) HashCrc32(s string) string

HashCrc32 generates a CRC32 hash for the input string

func (StringUtil) HashPassword added in v1.7.0

func (StringUtil) HashPassword(password string) (string, error)

HashPassword takes a plaintext password and returns its bcrypt hash

func (StringUtil) MD5

func (StringUtil) MD5(s string) string

MD5 generates an MD5 hash for the input string

func (StringUtil) ParseEMVCoQRString added in v1.13.1

func (s StringUtil) ParseEMVCoQRString(qrString string) (EMVCoQRInfo, error)

Parse EMVCoQR string to struct

func (StringUtil) RemoveAllSpaces

func (StringUtil) RemoveAllSpaces(s string) string

RemoveAllSpaces removes all spaces from the input string

func (StringUtil) RemoveDuplicateSpaces

func (StringUtil) RemoveDuplicateSpaces(s string) string

RemoveDuplicateSpaces removes duplicate spaces from the input string

func (StringUtil) SHA1

func (StringUtil) SHA1(s string) string

SHA1 generates a SHA1 hash for the input string

func (StringUtil) SHA256

func (StringUtil) SHA256(s string) string

SHA256 generates a SHA256 hash for the input string

func (StringUtil) UUID

func (StringUtil) UUID() string

UUID generates a new UUID string

func (StringUtil) ValidateEMVCoQRString added in v1.13.6

func (StringUtil) ValidateEMVCoQRString(qrString string) error

ValidateEMVCoQRString validates the EMVCoQR string

func (StringUtil) VerifyPassword added in v1.7.0

func (StringUtil) VerifyPassword(hashedPassword, password string) error

VerifyPassword checks if the provided plain text password matches the existing bcrypt hash

type TimeUtil

type TimeUtil struct{}

TimeUtil provides utility functions for working with time values

var Time TimeUtil

Time utility instance

func (TimeUtil) BeginningOfDay added in v1.13.7

func (TimeUtil) BeginningOfDay(value time.Time) time.Time

BeginningOfDay returns a time value of the beginning of the day

func (TimeUtil) BeginningOfMonth added in v1.13.7

func (TimeUtil) BeginningOfMonth(value time.Time) time.Time

BeginningOfMonth returns a time value of the beginning of the month

func (TimeUtil) BeginningOfWeek added in v1.13.7

func (TimeUtil) BeginningOfWeek(value time.Time) time.Time

BeginningOfWeek returns a time value of the beginning of the week

func (TimeUtil) BeginningOfYear added in v1.13.7

func (TimeUtil) BeginningOfYear(value time.Time) time.Time

BeginningOfYear returns a time value of the beginning of the year

func (TimeUtil) EndOfDay added in v1.13.7

func (TimeUtil) EndOfDay(value time.Time) time.Time

EndOfDay returns a time value of the end of the day

func (TimeUtil) EndOfMonth added in v1.13.7

func (TimeUtil) EndOfMonth(value time.Time) time.Time

EndOfMonth returns a time value of the end of the month

func (TimeUtil) EndOfWeek added in v1.13.7

func (TimeUtil) EndOfWeek(value time.Time) time.Time

EndOfWeek returns a time value of the end of the week

func (TimeUtil) EndOfYear added in v1.13.7

func (TimeUtil) EndOfYear(value time.Time) time.Time

EndOfYear returns a time value of the end of the year

func (TimeUtil) InBangkokTime

func (TimeUtil) InBangkokTime(value time.Time) time.Time

InBangkokTime returns a time value in the Bangkok time zone

func (TimeUtil) InHongKongTime

func (TimeUtil) InHongKongTime(value time.Time) time.Time

InHongKongTime returns a time value in the Hong Kong time zone

func (TimeUtil) IsTomorrow added in v1.13.7

func (TimeUtil) IsTomorrow(value time.Time) bool

IsTomorrow returns true if the specified time value is tomorrow

func (TimeUtil) IsYesterday added in v1.13.7

func (TimeUtil) IsYesterday(value time.Time) bool

IsYesterday returns true if the specified time value is yesterday

func (TimeUtil) ParseInBangkokLocation

func (TimeUtil) ParseInBangkokLocation(layout, value string) (time.Time, error)

ParseInBangkokLocation parses a string value in the Bangkok time zone with the specified layout

func (TimeUtil) ParseInHongKongLocation

func (TimeUtil) ParseInHongKongLocation(layout, value string) (time.Time, error)

ParseInHongKongLocation parses a string value in the Hong Kong time zone with the specified layout

func (TimeUtil) ToMySQLDate

func (TimeUtil) ToMySQLDate(value time.Time) string

ToMySQLDate returns a string value formatted as MySQL date with the specified time value

func (TimeUtil) ToMySQLDateTime

func (TimeUtil) ToMySQLDateTime(value time.Time) string

ToMySQLDateTime returns a string value formatted as MySQL datetime with the specified time value

func (TimeUtil) ToMySQLTime

func (TimeUtil) ToMySQLTime(value time.Time) string

ToMySQLTime returns a string value formatted as MySQL time with the specified time value

func (TimeUtil) Tomorrow added in v1.13.7

func (TimeUtil) Tomorrow(value time.Time) time.Time

Tomorrow returns a time value of tomorrow

func (TimeUtil) Yesterday added in v1.13.7

func (TimeUtil) Yesterday(value time.Time) time.Time

Yesterday returns a time value of yesterday

type ValidationError added in v1.4.0

type ValidationError struct {
	ErrorMessage string                     `json:"errorMessage"`      // Overall error message
	Details      []ValidationErrorDetail    `json:"details,omitempty"` // Optional list of error details
	Errors       validator.ValidationErrors `json:"-"`                 // The actual validation errors
}

ValidationError represents an error related to validation, with error details.

func ParseValidationError added in v1.4.0

func ParseValidationError(err error) ValidationError

ParseValidationError converts an error into a ValidationError. If the input error is a ValidationError, it's returned as is.

func (ValidationError) Error added in v1.4.0

func (e ValidationError) Error() string

Error function for ValidationError to return the error message

type ValidationErrorDetail added in v1.4.0

type ValidationErrorDetail struct {
	Field   string `json:"field" example:"ID"`                                                                              // Field that caused the validation error
	Tag     string `json:"tag" example:"required"`                                                                          // Validation tag that caused the error
	Message string `json:"message" example:"Key: 'Member.ID' Error:Field validation for 'ID' failed on the 'required' tag"` // Full error message
}

ValidationErrorDetail represents an individual error detail, with a field, tag, and message.

Jump to

Keyboard shortcuts

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