Documentation ¶
Index ¶
- Constants
- Variables
- func BoolToInt(b bool) int
- func DifferenceOf[T comparable](input ...[]T) []T
- func Filter[T any](s []T, f func(T) bool) []T
- func GetJSONTagName(field reflect.StructField) string
- func IntToBool(i int) bool
- func IntersectionOf[T comparable](input ...[]T) []T
- func IsArrayOrSlice(i any) bool
- func IsCommonError(err error) bool
- func IsValidationError(err error) bool
- func Map[T any](s []T, f func(T) T) []T
- func Max[T constraints.Ordered](x, y T) T
- func MaxOf[T constraints.Ordered](s []T) T
- func Min[T constraints.Ordered](x, y T) T
- func MinOf[T constraints.Ordered](s []T) T
- func PackageName() string
- func ParseFloat64(s string) (float64, error)
- func PointerOf[T any](v T) *T
- func RandomFloat64(min, max float64) float64
- func RandomInt64(min, max int64) int64
- func Reduce[T any](s []T, f func(prev T, curr T) T, initial T) T
- func SimpleSort[T constraints.Ordered](s []T) []T
- func SortFunc[T any](s []T, f func(T, T) bool) []T
- func UnionOf[T any](input ...[]T) []T
- func UniqueOf[T any](input []T) []T
- func ValidateNumberString(fl validator.FieldLevel) bool
- func ValidateStruct(s any) error
- func ValueOf[T any](ptr *T) T
- type AMQPClient
- func (client *AMQPClient) Close()
- func (client *AMQPClient) IsErrorClosed(err error) (error, bool)
- func (client *AMQPClient) NewPublisher(topic string) (*amqp.Sender, error)
- func (client *AMQPClient) NewReceiver(queue string) (*amqp.Receiver, error)
- func (client *AMQPClient) NewReceiverList(queue string, count int) ([]*amqp.Receiver, error)
- func (client *AMQPClient) NewSender(queue string) (*amqp.Sender, error)
- func (client *AMQPClient) NewSubscriber(topic string) (*amqp.Receiver, error)
- func (client *AMQPClient) Publish(publisher *amqp.Sender, message *amqp.Message) error
- func (client *AMQPClient) Received(receiver *amqp.Receiver, messageHandlerFunc AMQPMessageHandlerFunc)
- func (client *AMQPClient) ReceivedList(receiverList []*amqp.Receiver, messageHandlerFunc AMQPMessageHandlerFunc)
- func (client *AMQPClient) Send(sender *amqp.Sender, message *amqp.Message, persistent bool) error
- type AMQPConfig
- type AMQPMessageHandler
- type AMQPMessageHandlerFunc
- type AMQPUtil
- type Backend
- type CommonError
- type EMVCoQRInfo
- type EchoBinderWithValidation
- func (b *EchoBinderWithValidation) Bind(i any, c echo.Context) error
- func (b *EchoBinderWithValidation) BindAll(i any, c echo.Context) error
- func (b *EchoBinderWithValidation) BindBody(c echo.Context, i any) error
- func (b *EchoBinderWithValidation) BindHeaders(c echo.Context, i any) error
- func (b *EchoBinderWithValidation) BindPathParams(c echo.Context, i any) error
- func (b *EchoBinderWithValidation) BindQueryParams(c echo.Context, i any) error
- type EchoJWTConfig
- type EchoJWTUtil
- func (eJWT EchoJWTUtil) CreateToken(claims jwt.RegisteredClaims) JWTToken
- func (eJWT EchoJWTUtil) GetClaims(token *jwt.Token) (*jwt.RegisteredClaims, error)
- func (eJWT EchoJWTUtil) JWTAuth() echo.MiddlewareFunc
- func (eJWT EchoJWTUtil) KeyFunc(token *jwt.Token) (any, error)
- func (EchoJWTUtil) New(config *EchoJWTConfig) *EchoJWTUtil
- func (eJWT EchoJWTUtil) ParseToken(signedToken string) (*jwt.Token, error)
- func (eJWT EchoJWTUtil) ParseTokenFunc(c echo.Context, auth string) (any, error)
- func (eJWT *EchoJWTUtil) SetSkipper(skipper middleware.Skipper)
- type EchoUtil
- type EchoValidator
- type ErrorResponse
- type ImageUtil
- type JWTToken
- type JsonUtil
- type RedisClient
- func (r *RedisClient) GetStruct(key string, result any) error
- func (r *RedisClient) JSONGet(key string, result any) error
- func (r *RedisClient) JSONSet(key string, value any, expiration time.Duration) error
- func (r *RedisClient) SetNXStruct(key string, value any, expiration time.Duration) (bool, error)
- func (r *RedisClient) SetStruct(key string, value any, expiration time.Duration) error
- type RedisConfig
- type RedisUtil
- type Result
- type Session
- type SessionHandler
- type SessionMeta
- type SessionRedisConfig
- type SessionRedisHandler
- func (h *SessionRedisHandler) Count(uniqueByUser bool) (int, error)
- func (h *SessionRedisHandler) CountByGroupID(groupId string, uniqueByUser bool) (int, error)
- func (h *SessionRedisHandler) CountByUserID(userId int64, uniqueByUser bool) (int, error)
- func (h *SessionRedisHandler) Delete(meta SessionMeta) error
- func (h *SessionRedisHandler) DeleteAll() error
- func (h *SessionRedisHandler) DeleteByGroupID(groupId string) error
- func (h *SessionRedisHandler) DeleteByUserID(userId int64) error
- func (h *SessionRedisHandler) Exists(meta SessionMeta) (bool, error)
- func (h *SessionRedisHandler) Get(meta SessionMeta) (Session, error)
- func (h *SessionRedisHandler) ListByGroupID(groupId string) ([]Session, error)
- func (h *SessionRedisHandler) ListByUserID(userId int64) ([]Session, error)
- func (h *SessionRedisHandler) Set(s Session, expiresAt int64) error
- type StringUtil
- func (StringUtil) AESDecrypt(key, cipherText string) (string, error)
- func (StringUtil) AESEncrypt(key, plaintext string) (string, error)
- func (StringUtil) HashCrc32(s string) string
- func (StringUtil) HashPassword(password string) (string, error)
- func (StringUtil) MD5(s string) string
- func (s StringUtil) ParseEMVCoQRString(qrString string) (EMVCoQRInfo, error)
- func (StringUtil) RemoveAllSpaces(s string) string
- func (StringUtil) RemoveDuplicateSpaces(s string) string
- func (StringUtil) SHA1(s string) string
- func (StringUtil) SHA256(s string) string
- func (StringUtil) UUID() string
- func (StringUtil) ValidateEMVCoQRString(qrString string) error
- func (StringUtil) VerifyPassword(hashedPassword, password string) error
- type TimeUtil
- func (TimeUtil) BeginningOfDay(value time.Time) time.Time
- func (TimeUtil) BeginningOfMonth(value time.Time) time.Time
- func (TimeUtil) BeginningOfWeek(value time.Time) time.Time
- func (TimeUtil) BeginningOfYear(value time.Time) time.Time
- func (TimeUtil) EndOfDay(value time.Time) time.Time
- func (TimeUtil) EndOfMonth(value time.Time) time.Time
- func (TimeUtil) EndOfWeek(value time.Time) time.Time
- func (TimeUtil) EndOfYear(value time.Time) time.Time
- func (TimeUtil) InBangkokTime(value time.Time) time.Time
- func (TimeUtil) InHongKongTime(value time.Time) time.Time
- func (TimeUtil) IsTomorrow(value time.Time) bool
- func (TimeUtil) IsYesterday(value time.Time) bool
- func (TimeUtil) ParseInBangkokLocation(layout, value string) (time.Time, error)
- func (TimeUtil) ParseInHongKongLocation(layout, value string) (time.Time, error)
- func (TimeUtil) ToMySQLDate(value time.Time) string
- func (TimeUtil) ToMySQLDateTime(value time.Time) string
- func (TimeUtil) ToMySQLTime(value time.Time) string
- func (TimeUtil) Tomorrow(value time.Time) time.Time
- func (TimeUtil) Yesterday(value time.Time) time.Time
- type ValidationError
- type ValidationErrorDetail
Examples ¶
Constants ¶
const ( ErrCodeSomethingWentWrong = "SOMETHING_WENT_WRONG" ErrCodeBadRequest = "BAD_REQUEST" )
Error code constants
const ( ErrMessageSomethingWentWrong = "Something went wrong" ErrMessageBadRequest = "Bad request" )
Error message constants
const ( DefaultRedisSessionKey = "session" DefaultRedisUserKey = "user" )
Default keys for storing session and user data in Redis.
const ( MySQLDateTimeLayout = "2006-01-02 15:04:05" MySQLDateLayout = "2006-01-02" MySQLTimeLayout = "15:04:05" )
const ( AsiaBangkokLocation = "Asia/Bangkok" AsiaHongKongLocation = "Asia/Hong_Kong" )
Variables ¶
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. )
var (
BangkokTimeLocation, _ = time.LoadLocation(AsiaBangkokLocation)
HongKongTimeLocation, _ = time.LoadLocation(AsiaHongKongLocation)
)
time.Location instances
var (
ErrNotAnImage = errors.New("not an image")
)
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.
var Validate = validator.New()
Validate a new instance of the validator library.
Functions ¶
func BoolToInt ¶ added in v1.3.0
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
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
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 ¶
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
IsCommonError returns true if the given error is a CommonError.
func IsValidationError ¶ added in v1.4.0
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 ¶
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 ¶
RandomFloat64 generates a random float64 value between min and max.
Example ¶
fmt.Println(utils.RandomFloat64(10.5, 10.5))
Output: 10.5
func RandomInt64 ¶
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
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
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.
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
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
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
func LoadBalancedByWeight ¶ added in v1.13.3
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
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
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) FromMultipart ¶ added in v1.13.12
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
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) SetNXStruct ¶ added in v1.8.0
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)
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.
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.
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) 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
BeginningOfDay returns a time value of the beginning of the day
func (TimeUtil) BeginningOfMonth ¶ added in v1.13.7
BeginningOfMonth returns a time value of the beginning of the month
func (TimeUtil) BeginningOfWeek ¶ added in v1.13.7
BeginningOfWeek returns a time value of the beginning of the week
func (TimeUtil) BeginningOfYear ¶ added in v1.13.7
BeginningOfYear returns a time value of the beginning of the year
func (TimeUtil) EndOfMonth ¶ added in v1.13.7
EndOfMonth returns a time value of the end of the month
func (TimeUtil) InBangkokTime ¶
InBangkokTime returns a time value in the Bangkok time zone
func (TimeUtil) InHongKongTime ¶
InHongKongTime returns a time value in the Hong Kong time zone
func (TimeUtil) IsTomorrow ¶ added in v1.13.7
IsTomorrow returns true if the specified time value is tomorrow
func (TimeUtil) IsYesterday ¶ added in v1.13.7
IsYesterday returns true if the specified time value is yesterday
func (TimeUtil) ParseInBangkokLocation ¶
ParseInBangkokLocation parses a string value in the Bangkok time zone with the specified layout
func (TimeUtil) ParseInHongKongLocation ¶
ParseInHongKongLocation parses a string value in the Hong Kong time zone with the specified layout
func (TimeUtil) ToMySQLDate ¶
ToMySQLDate returns a string value formatted as MySQL date with the specified time value
func (TimeUtil) ToMySQLDateTime ¶
ToMySQLDateTime returns a string value formatted as MySQL datetime with the specified time value
func (TimeUtil) ToMySQLTime ¶
ToMySQLTime returns a string value formatted as MySQL time with the specified time value
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.