Documentation ¶
Overview ¶
Package helper: common project provides commonly used helper utility functions, custom utility types, and third party package wrappers. common project helps code reuse, and faster composition of logic without having to delve into commonly recurring code logic and related testings. common project source directories and brief description: + /ascii = helper types and/or functions related to ascii manipulations. + /crypto = helper types and/or functions related to encryption, decryption, hashing, such as rsa, aes, sha, tls etc. + /csv = helper types and/or functions related to csv file manipulations. + /rest = helper types and/or functions related to http rest api GET, POST, PUT, DELETE actions invoked from client side. + /tcp = helper types providing wrapped tcp client and tcp server logic. - /wrapper = wrappers provides a simpler usage path to third party packages, as well as adding additional enhancements.
- /aws = contains aws sdk helper types and functions.
- /cloudmap = wrapper for aws cloudmap service discovery.
- /dynamodb = wrapper for aws dynamodb data access and manipulations.
- /gin = wrapper for gin-gonic web server, and important middleware, into a ready to use solution.
- /hystrixgo = wrapper for circuit breaker logic.
- /kms = wrapper for aws key management services.
- /mysql = wrapper for mysql + sqlx data access and manipulation.
- /ratelimit = wrapper for ratelimit logic.
- /redis = wrapper for redis data access and manipulation, using go-redis.
- /s3 = wrapper for aws s3 data access and manipulation.
- /ses = wrapper for aws simple email services.
- /sns = wrapper for aws simple notification services.
- /sqlite = wrapper for sqlite + sqlx data access and manipulation.
- /sqlserver = wrapper for sqlserver + sqlx data access and manipulation.
- /sqs = wrapper for aws simple queue services.
- /systemd = wrapper for kardianos service to support systemd, windows, launchd service creations.
- /viper = wrapper for viper config.
- /waf2 = wrapper for aws waf2 (web application firewall v2).
- /xray = wrapper for aws xray distributed tracing.
- /zap = wrapper for zap logging.
/helper-conv.go = helpers for data conversion operations. /helper-db.go = helpers for database data type operations. /helper-emv.go = helpers for emv chip card related operations. /helper-io.go = helpers for io related operations. /helper-net.go = helpers for network related operations. /helper-num.go = helpers for numeric related operations. /helper-other.go = helpers for misc. uncategorized operations. /helper-reflect.go = helpers for reflection based operations. /helper-regex.go = helpers for regular express related operations. /helper-str.go = helpers for string operations. /helper-struct.go = helpers for struct related operations. /helper-time.go = helpers for time related operations. /helper-uuid.go = helpers for generating globally unique ids.
Index ¶
- func AbsDuration(d time.Duration) time.Duration
- func AbsFloat64(f float64) float64
- func AbsInt(i int) int
- func AbsInt64(i int64) int64
- func Atob(s string) bool
- func Atoi(s string) int
- func Base64StdDecode(data string) (string, error)
- func Base64StdEncode(data string) string
- func Base64UrlDecode(data string) (string, error)
- func Base64UrlEncode(data string) string
- func BoolPtr(b bool) *bool
- func BoolPtrToBool(b *bool) bool
- func BoolToInt(b bool) int
- func BoolToString(b bool) string
- func BoolVal(b *bool) bool
- func Btoa(b bool) string
- func ByteToHex(data []byte) string
- func CentsToFloat64(i int) float64
- func ConsolePromptAndAnswer(prompt string, replyLowercase bool, autoTrim ...bool) string
- func ConsolePromptAndAnswerBool(prompt string, defaultTrue ...bool) bool
- func ConsolePromptAndAnswerFloat64(prompt string, preventNegative ...bool) float64
- func ConsolePromptAndAnswerInt(prompt string, preventNegative ...bool) int
- func CopyDir(src string, dst string) error
- func CopyFile(src string, dst string) error
- func CurrentDate() string
- func CurrentDateStruct() time.Time
- func CurrentDateTime() string
- func CurrentDateTimeStruct() time.Time
- func CurrentTime() string
- func DateAfter(testDate time.Time, afterDate time.Time) bool
- func DateAfterOrEqual(testDate time.Time, afterEqualDate time.Time) bool
- func DateBefore(testDate time.Time, beforeDate time.Time) bool
- func DateBeforeOrEqual(testDate time.Time, beforeEqualDate time.Time) bool
- func DateBetween(testDate time.Time, fromDate time.Time, toDate time.Time, ...) bool
- func DateEqual(testDate time.Time, equalDate time.Time) bool
- func DateFormatString() string
- func DateOutside(testDate time.Time, fromDate time.Time, toDate time.Time) bool
- func DatePtrToString(t *time.Time) string
- func DateTimeFormatString() string
- func DateTimePtrToDateTime(t *time.Time) time.Time
- func DateTimePtrToString(t *time.Time) string
- func DateToLocal(t time.Time) (time.Time, error)
- func DateToLocal2(t time.Time) time.Time
- func DateToUTC(t time.Time) (time.Time, error)
- func DateToUTC2(t time.Time) time.Time
- func DaysDiff(timeFrom time.Time, timeTo time.Time) int
- func DerefError(v reflect.Value) error
- func DerefPointersZero(rv reflect.Value) (drv reflect.Value, isPtr bool, isNilPtr bool)
- func DnsLookupIps(host string) (ipList []net.IP)
- func DnsLookupSrvs(host string) (ipList []string)
- func DurationPtr(d time.Duration) *time.Duration
- func DurationVal(d *time.Duration) time.Duration
- func EncodeHttpHeaderMapToString(headerMap map[string]string) string
- func ExponentialToNumber(exp string) string
- func ExtractAlpha(s string) (string, error)
- func ExtractAlphaNumeric(s string) (string, error)
- func ExtractAlphaNumericPrintableSymbols(s string) (string, error)
- func ExtractAlphaNumericUnderscoreDash(s string) (string, error)
- func ExtractByRegex(s string, regexStr string) (string, error)
- func ExtractHex(s string) (string, error)
- func ExtractNumeric(s string) (string, error)
- func FileExists(path string) bool
- func FileRead(path string) (string, error)
- func FileReadBytes(path string) ([]byte, error)
- func FileWrite(path string, data string) error
- func FileWriteBytes(path string, data []byte) error
- func Fill(src interface{}, dst interface{}) error
- func Float32Ptr(f float32) *float32
- func Float32PtrToFloat32(f *float32) float32
- func Float32ToString(f float32) string
- func Float32ToStringCents(f float32) string
- func Float64Ptr(f float64) *float64
- func Float64PtrToFloat64(f *float64) float64
- func Float64ToInt(f float64) int
- func Float64ToIntCents(f float64) int
- func Float64ToString(f float64) string
- func Float64Val(f *float64) float64
- func FloatToString(f float64) string
- func FormatDate(t time.Time, blankIfZero ...bool) string
- func FormatDateTime(t time.Time, blankIfZero ...bool) string
- func FormatDateTimeToISO8601_RFC3339(t time.Time, blankIfZero ...bool) string
- func FormatDateTimeToMMDDYYYYhhmmss(t time.Time) string
- func FormatDateTimeToYYYYMMDDhhmmss(t time.Time) string
- func FormatDateToDDMMYYYY(t time.Time) string
- func FormatDateToMMDD(t time.Time) string
- func FormatDateToMMYY(t time.Time) string
- func FormatDateToYYMM(t time.Time) string
- func FormatDateToYYMMDD(t time.Time) string
- func FormatDateToYYYYMMDD(t time.Time) string
- func FormatTime(t time.Time, blankIfZero ...bool) string
- func FormatTimeTohhmmss(t time.Time) string
- func FromNullBool(b sql.NullBool) bool
- func FromNullFloat32(d sql.NullFloat64) float32
- func FromNullFloat64(d sql.NullFloat64) float64
- func FromNullInt(d sql.NullInt32) int
- func FromNullInt64(d sql.NullInt64) int64
- func FromNullString(s sql.NullString) string
- func FromNullTime(t sql.NullTime) time.Time
- func GenerateNewUniqueInt32(oldIntVal int) int
- func GenerateNewUniqueInt64(oldIntVal int64) int64
- func GenerateNewUniqueNullInt32(oldIntVal sql.NullInt32) sql.NullInt32
- func GenerateNewUniqueNullInt64(oldIntVal sql.NullInt64) sql.NullInt64
- func GenerateNewUniqueNullString(oldStrVal sql.NullString, stringLimit int) sql.NullString
- func GenerateNewUniqueString(oldStrVal string, stringLimit int) string
- func GenerateRandomChar() string
- func GenerateRandomNumber(maxNumber int) int
- func GenerateULID() (string, error)
- func GenerateUUIDv4() (string, error)
- func GetDate(year int, month int, day int) time.Time
- func GetFirstBoolOrDefault(defaultValue bool, paramValue ...bool) bool
- func GetFirstByteOrDefault(defaultValue byte, paramValue ...byte) byte
- func GetFirstDateOfMonth(t time.Time) time.Time
- func GetFirstFloat32OrDefault(defaultValue float32, paramValue ...float32) float32
- func GetFirstFloat64OrDefault(defaultValue float64, paramValue ...float64) float64
- func GetFirstInt64OrDefault(defaultValue int64, paramValue ...int64) int64
- func GetFirstIntOrDefault(defaultValue int, paramValue ...int) int
- func GetFirstOrDefault(defaultValue interface{}, paramValue ...interface{}) interface{}
- func GetFirstStringOrDefault(defaultValue string, paramValue ...string) string
- func GetFirstTimeOrDefault(defaultValue time.Time, paramValue ...time.Time) time.Time
- func GetLastDateOfMonth(t time.Time) time.Time
- func GetLocalIP() string
- func GetNetListener(port uint) (net.Listener, error)
- func GetStructTagValueByObject(structObj interface{}, structFieldName string, structTagName string) (notFound bool, tagValue string, t reflect.Type)
- func GetStructTagValueByType(t reflect.Type, structFieldName string, structTagName string) (notFound bool, tagValue string)
- func GetStructTagsValueSlice(field reflect.StructField, tagName ...string) (tagValues []string)
- func HTMLDecode(s string) string
- func HTMLEncode(s string) string
- func HexToByte(hexData string) ([]byte, error)
- func HexToString(hexData string) (string, error)
- func HoursDiff(timeFrom time.Time, timeTo time.Time) int
- func Int32PtrToInt(n *int) int
- func Int64Ptr(i int64) *int64
- func Int64PtrToInt64(n *int64) int64
- func Int64ToString(n int64) string
- func Int64Val(i *int64) int64
- func IntPtr(i int) *int
- func IntSliceContains(intSlice *[]int, value int) bool
- func IntToHex(i int) string
- func IntVal(i *int) int
- func IsAlphanumericAndSpaceOnly(s string) bool
- func IsAlphanumericOnly(s string) bool
- func IsBase64Only(s string) bool
- func IsBoolType(s string) bool
- func IsDateTimeValidYYMMDDhhmm(s string) bool
- func IsDateTimeValidYYMMDDhhmmss(s string) bool
- func IsDateTimeValidYYYYMMDDhhmm(s string) bool
- func IsDateTimeValidYYYYMMDDhhmmss(s string) bool
- func IsDateValidMMDDYY(s string) bool
- func IsDateValidMMDDYYYY(s string) bool
- func IsDateValidMMYY(s string) bool
- func IsDateValidMMYYYY(s string) bool
- func IsDateValidYYMM(s string) bool
- func IsDateValidYYMMDD(s string) bool
- func IsDateValidYYYYMM(s string) bool
- func IsDateValidYYYYMMDD(s string) bool
- func IsDayOfMonthValid(year int, month int, day int) bool
- func IsFloat32(s string) bool
- func IsFloat64(s string) bool
- func IsHexOnly(s string) bool
- func IsHttpsEndpoint(url string) bool
- func IsInt32(s string) bool
- func IsInt64(s string) bool
- func IsLeapYear(year int) bool
- func IsNumericFloat64(s string, positiveOnly bool) bool
- func IsNumericIntAndNegativeSignOnly(s string) bool
- func IsNumericIntOnly(s string) bool
- func IsStructFieldSet(inputStructPtr interface{}) bool
- func IsTimeValidhhmm(s string) bool
- func IsTimeValidhhmmss(s string) bool
- func Itoa(i int) string
- func ItoaZeroBlank(i int) string
- func JsonFromEscaped(data string) string
- func JsonToEscaped(data string) string
- func Left(s string, l int) string
- func LenTrim(s string) int
- func LenTrimNullString(s sql.NullString) int
- func MarshalJSONCompact(v interface{}) (string, error)
- func MarshalJSONIndent(v interface{}) (string, error)
- func MarshalSliceStructToJson(inputSliceStructPtr []interface{}, tagName string, excludeTagName string) (jsonArrayOutput string, err error)
- func MarshalStructToCSV(inputStructPtr interface{}, csvDelimiter string) (csvPayload string, err error)
- func MarshalStructToJson(inputStructPtr interface{}, tagName string, excludeTagName string) (string, error)
- func MarshalStructToQueryParams(inputStructPtr interface{}, tagName string, excludeTagName string) (string, error)
- func MarshalXML(v interface{}, indentXML bool) (string, error)
- func MarshalXMLCompact(v interface{}) (string, error)
- func MarshalXMLIndent(v interface{}) (string, error)
- func Mid(s string, start int, l int) string
- func MinutesDiff(timeFrom time.Time, timeTo time.Time) int
- func NewULID() string
- func NewUUID() string
- func NextFixedLength(data string, blockSize int) int
- func PadLeft(data string, totalSize int) string
- func PadRight(data string, totalSize int) string
- func PadX(data string, totalSize int, padRight ...bool) string
- func PadZero(data string, totalSize int, padRight ...bool) string
- func Padding(data string, totalSize int, padRight bool, padChar string) string
- func ParseBool(s string) (bool, bool)
- func ParseDate(s string) time.Time
- func ParseDateFromDDMMYYYY(s string) time.Time
- func ParseDateFromMMDD(s string) time.Time
- func ParseDateFromMMYY(s string) time.Time
- func ParseDateFromYYMM(s string) time.Time
- func ParseDateFromYYMMDD(s string) time.Time
- func ParseDateFromYYYYMMDD(s string) time.Time
- func ParseDateTime(s string) time.Time
- func ParseDateTime24Hr(s string) time.Time
- func ParseDateTimeCustom(s string, f string) time.Time
- func ParseDateTimeFromMMDDYYYYhhmmss(s string) time.Time
- func ParseDateTimeFromYYYYMMDDhhmmss(s string) time.Time
- func ParseDateToLastDayOfMonth(t time.Time) time.Time
- func ParseEmvTlvTagNamesOnly(emvTlvTagNamesPayload string) (foundList []string, err error)
- func ParseFloat32(s string) (float32, bool)
- func ParseFloat64(s string) (float64, bool)
- func ParseFromExcelDate(s string, format string) time.Time
- func ParseHostFromURL(url string) string
- func ParseHttpHeader(respHeader http.Header) (map[string]string, error)
- func ParseInt32(s string) (int, bool)
- func ParseInt64(s string) (int64, bool)
- func ParseKeyValue(s string, delimiter string, key *string, val *string) error
- func ParseTime(s string) time.Time
- func ParseTimeFromhhmmss(s string) time.Time
- func ReadHttpRequestBody(req *http.Request) ([]byte, error)
- func ReadHttpRequestHeaders(req *http.Request) (map[string]string, error)
- func ReflectCall(o reflect.Value, methodName string, paramValue ...interface{}) (resultSlice []reflect.Value, notFound bool)
- func ReflectGetType(obj interface{}) reflect.Type
- func ReflectObjectNewPtr(objType reflect.Type) interface{}
- func ReflectStringToField(o reflect.Value, v string, timeFormat string) error
- func ReflectTypeRegistryAdd(customStructObj interface{}, customFullTypeName ...string) bool
- func ReflectTypeRegistryCount() int
- func ReflectTypeRegistryGet(customFullTypeName string) reflect.Type
- func ReflectTypeRegistryRemove(customFullTypeName string)
- func ReflectTypeRegistryRemoveAll()
- func ReflectValueToString(o reflect.Value, boolTrue string, boolFalse string, skipBlank bool, ...) (valueStr string, skip bool, err error)
- func RegexReplaceSubString(source string, subStringFrom string, subStringTo string, replaceWith string, ...) string
- func Replace(s string, oldChar string, newChar string) string
- func Reverse(s string) string
- func Right(s string, l int) string
- func RightTrimLF(s string) string
- func SecondsDiff(timeFrom time.Time, timeTo time.Time) int
- func SetStructFieldDefaultValues(inputStructPtr interface{}) bool
- func SliceDeleteElement(slice interface{}, removalIndex int) (resultSlice interface{})
- func SliceObjectsToSliceInterface(objectsSlice interface{}) (output []interface{})
- func SliceSeekElement(slice []interface{}, ...) interface{}
- func SliceStringToCSVString(source []string, spaceAfterComma bool) string
- func SplitString(source string, delimiter string, index int) string
- func StrToUint(s string) uint
- func StrToUint64(s string) uint64
- func StringPtr(s string) *string
- func StringPtrToString(s *string) string
- func StringSliceContains(strSlice *[]string, value string) bool
- func StringSliceExtractUnique(strSlice []string) (result []string)
- func StringToHex(data string) string
- func StringVal(s *string) string
- func StructClearFields(inputStructPtr interface{})
- func StructNonDefaultRequiredFieldsCount(inputStructPtr interface{}) int
- func TimeFormatString() string
- func TimePtr(t time.Time) *time.Time
- func TimeVal(t *time.Time) time.Time
- func ToNullBool(b bool) sql.NullBool
- func ToNullFloat32(d float32, emptyAsNull bool) sql.NullFloat64
- func ToNullFloat64(d float64, emptyAsNull bool) sql.NullFloat64
- func ToNullInt(d int, emptyAsNull bool) sql.NullInt32
- func ToNullInt64(d int64, emptyAsNull bool) sql.NullInt64
- func ToNullString(s string, emptyAsNull bool) sql.NullString
- func ToNullTime(t time.Time) sql.NullTime
- func Trim(s string) string
- func UInt64ToString(n uint64) string
- func UintPtr(i uint) *uint
- func UintToStr(i uint) string
- func UintVal(i *uint) uint
- func UnmarshalCSVToStruct(inputStructPtr interface{}, csvPayload string, csvDelimiter string, ...) error
- func UnmarshalJSON(jsonData string, v interface{}) error
- func UnmarshalJsonToStruct(inputStructPtr interface{}, jsonPayload string, tagName string, ...) error
- func UnmarshalXML(xmlData string, v interface{}) error
- func VerifyGoogleReCAPTCHAv2(response string, secret string) (success bool, challengeTs time.Time, hostName string, err error)
- func XMLFromEscaped(data string) string
- func XMLToEscaped(data string) string
- type EmvTlvTag
- type JsonTime
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func AbsDuration ¶ added in v1.1.2
AbsDuration returns absolute value of d
func AbsFloat64 ¶ added in v1.0.9
AbsFloat64 returns absolute value of f
func Atob ¶
Atob converts string to bool. string values with first char lower cased "t", "y", "1" treated as true, otherwise false.
func Base64StdDecode ¶
Base64StdDecode will decode given data from base 64 standard encoded string
func Base64StdEncode ¶
Base64StdEncode will encode given data into base 64 standard encoded string
func Base64UrlDecode ¶
Base64UrlDecode will decode given data from base 64 url encoded string
func Base64UrlEncode ¶
Base64UrlEncode will encode given data into base 64 url encoded string
func BoolPtrToBool ¶
BoolPtrToBool converts bool pointer to bool value.
func BoolToString ¶ added in v1.1.1
BoolToString converts bool to string value, true = "true", false = "false".
func BoolVal ¶ added in v1.1.1
BoolVal gets bool value from bool pointer, if pointer is nil, false is returned.
func CentsToFloat64 ¶ added in v1.1.4
CentsToFloat64 converts int (cents) into float64 value with two decimal value.
func ConsolePromptAndAnswer ¶ added in v1.0.9
ConsolePromptAndAnswer is a helper to prompt a message and then scan a response in console
func ConsolePromptAndAnswerBool ¶ added in v1.0.9
ConsolePromptAndAnswerBool is a helper to prompt a message and then scan a response in console
func ConsolePromptAndAnswerFloat64 ¶ added in v1.0.9
ConsolePromptAndAnswerFloat64 is a helper to prompt a message and then scan a response in console
func ConsolePromptAndAnswerInt ¶ added in v1.0.9
ConsolePromptAndAnswerInt is a helper to prompt a message and then scan a response in console
func CurrentDateStruct ¶
CurrentDateStruct returns current date in yyyy-mm-dd format via time.Time struct
func CurrentDateTime ¶
func CurrentDateTime() string
CurrentDateTime returns current date and time in yyyy-mm-dd hh:mm:ss tt format
func CurrentDateTimeStruct ¶
CurrentDateTimeStruct returns current date and time in yyyy-mm-dd hh:mm:ss tt format via time.Time struct
func DateAfterOrEqual ¶
DateAfterOrEqual checks if testDate is after or equal to the afterEqualDate
func DateBefore ¶
DateBefore checks if testDate is before the beforeDate
func DateBeforeOrEqual ¶
DateBeforeOrEqual checks if testDate is before or equal to the beforeEqualDate
func DateBetween ¶
func DateBetween(testDate time.Time, fromDate time.Time, toDate time.Time, doNotIncludeEqual bool) bool
DateBetween checks if testDate is within the fromDate and toDate, if doNotIncludeEqual = true, then testDate equals fromDate and toDate are skipped
func DateFormatString ¶
func DateFormatString() string
DateFormatString returns the date format string constant (yyyy-mm-dd)
func DateOutside ¶
DateOutside checks if the testDate is outside of the fromDate and toDate
func DatePtrToString ¶
DatePtrToString formats pointer time.Time to string date format yyyy-mm-dd.
func DateTimeFormatString ¶
func DateTimeFormatString() string
DateTimeFormatString returns the date time format string constant (yyyy-mm-dd hh:mm:ss tt)
func DateTimePtrToDateTime ¶
DateTimePtrToDateTime formats pointer time.Time to time.Time struct.
func DateTimePtrToString ¶
DateTimePtrToString formats pointer time.Time to string date time format yyyy-mm-dd hh:mm:ss AM/PM.
func DateToLocal ¶
DateToLocal converts given time to local time
func DateToLocal2 ¶
DateToLocal2 returns local value directly without error info
func DateToUTC2 ¶
DateToUTC2 returns utc value directly without error info
func DerefError ¶ added in v1.1.1
DerefError dereferences reflect.Value to error object if underlying type was error
func DerefPointersZero ¶ added in v1.1.1
DerefPointersZero gets pointer base type
func DnsLookupIps ¶
DnsLookupIps returns list of IPs for the given host if host is private on aws route 53, then lookup ip will work only when within given aws vpc that host was registered with
func DnsLookupSrvs ¶
DnsLookupSrvs returns list of IP and port addresses based on host if host is private on aws route 53, then lookup ip will work only when within given aws vpc that host was registered with
func DurationPtr ¶
DurationPtr casts Duration to Duration pointer.
func DurationVal ¶ added in v1.1.1
DurationVal gets Duration value from Duration pointer, if pointer is nil, 0 is returned.
func EncodeHttpHeaderMapToString ¶ added in v1.1.4
EncodeHttpHeaderMapToString converts header map[string]string to string representation
func ExponentialToNumber ¶ added in v1.0.9
ExponentialToNumber converts exponential representation of a number into actual number equivalent
func ExtractAlpha ¶ added in v1.1.1
ExtractAlpha will extract A-Z out of string to be returned
func ExtractAlphaNumeric ¶
ExtractAlphaNumeric will extract only A-Z, a-z, and 0-9 out of string to be returned
func ExtractAlphaNumericPrintableSymbols ¶ added in v1.1.1
ExtractAlphaNumericPrintableSymbols will extra A-Z, a-z, 0-9, and printable symbols
func ExtractAlphaNumericUnderscoreDash ¶ added in v1.1.1
ExtractAlphaNumericUnderscoreDash will extract only A-Z, a-z, 0-9, _, - out of string to be returned
func ExtractByRegex ¶ added in v1.1.1
ExtractByRegex will extract string based on regex expression, any regex match will be replaced with blank
func ExtractHex ¶ added in v1.1.2
ExtractHex will extract only A-F, a-f, and 0-9 out of string to be returned
func ExtractNumeric ¶
ExtractNumeric will extract only 0-9 out of string to be returned
func FileRead ¶
FileRead will read all file content of given file in path, return as string if successful, if failed, error will contain the error reason
func FileReadBytes ¶ added in v1.0.9
FileReadBytes will read all file content and return slice of byte
func FileWrite ¶
FileWrite will write data into file at the given path, if successful, no error is returned (nil)
func FileWriteBytes ¶ added in v1.0.9
FileWriteBytes will write byte data into file at the given path, if successful, no error is returned (nil)
func Fill ¶ added in v1.0.4
func Fill(src interface{}, dst interface{}) error
Fill copies the src struct with same tag name to dst struct tag pointer, src and dst both must be struct,and dst must be pointer
func Float32Ptr ¶
Float32Ptr gets float32 pointer from float32 value.
func Float32PtrToFloat32 ¶
Float32PtrToFloat32 returns 0 if pointer is nil, otherwise actual float32 value.
func Float32ToString ¶
Float32ToString converts float32 value to string.
func Float32ToStringCents ¶
Float32ToStringCents converts float32 value into string representing cent values, 2.12 returned as "212". Since float32 can not be precisely calculated in some cases, use math.Round returns the nearest integer
func Float64Ptr ¶
Float64Ptr gets float64 pointer from float64 value.
func Float64PtrToFloat64 ¶
Float64PtrToFloat64 returns 0 if nil, otherwise actual float64 value.
func Float64ToInt ¶
Float64ToInt converts from float64 into int, if conversion fails, 0 is returned.
func Float64ToIntCents ¶ added in v1.1.2
Float64ToIntCents converts float64 value into int, representing cent values, 2.12 returned as 212. Since float64 can not be precisely calculated in some cases, use math.Round returns the nearest integer
func Float64ToString ¶ added in v1.1.1
Float64ToString converts float64 value into string value.
func Float64Val ¶ added in v1.1.1
Float64Val gets float64 value from float64 pointer, if pointer is nil, 0 is returned.
func FloatToString ¶
FloatToString converts float64 value into string value.
func FormatDate ¶
FormatDate will format the input date value to yyyy-mm-dd
func FormatDateTime ¶
FormatDateTime will format the input date value to yyyy-mm-dd hh:mm:ss tt
func FormatDateTimeToISO8601_RFC3339 ¶ added in v1.2.7
FormatDateTimeToISO8601_RFC3339 accepts time struct and converts to iso8601 string output format
func FormatDateTimeToMMDDYYYYhhmmss ¶
FormatDateTimeToMMDDYYYYhhmmss for the date time struct received
func FormatDateTimeToYYYYMMDDhhmmss ¶
FormatDateTimeToYYYYMMDDhhmmss for the date time struct received
func FormatDateToDDMMYYYY ¶
FormatDateToDDMMYYYY for the date time struct received
func FormatDateToMMDD ¶
FormatDateToMMDD for the date time struct received
func FormatDateToMMYY ¶
FormatDateToMMYY for the date time struct received
func FormatDateToYYMM ¶
FormatDateToYYMM for the date time struct received
func FormatDateToYYMMDD ¶
FormatDateToYYMMDD for the date time struct received
func FormatDateToYYYYMMDD ¶
FormatDateToYYYYMMDD for the date time struct received
func FormatTime ¶
FormatTime will format the input date value to hh:mm:ss tt
func FormatTimeTohhmmss ¶ added in v1.1.5
FormatTimeTohhmmss for the date time struct received
func FromNullBool ¶
FromNullBool casts sql null bool variable to bool variable, if null, false is returned
func FromNullFloat32 ¶
func FromNullFloat32(d sql.NullFloat64) float32
FromNullFloat32 casts sql null float64 into float32 variable
func FromNullFloat64 ¶
func FromNullFloat64(d sql.NullFloat64) float64
FromNullFloat64 casts sql null float64 variable to float64 variable, if null, 0.00 is returned
func FromNullInt ¶
FromNullInt casts sql NullInt32 into int variable, if null, 0 is returned
func FromNullInt64 ¶
FromNullInt64 casts sql null int64 variable to int64 variable, if null, 0 is returned
func FromNullString ¶
func FromNullString(s sql.NullString) string
FromNullString casts sql null string variable to string variable, if null, blank string is returned
func FromNullTime ¶
FromNullTime parses string into time.Time
func GenerateNewUniqueInt32 ¶
GenerateNewUniqueInt32 will take in old value and return new unique value with randomized seed and negated
func GenerateNewUniqueInt64 ¶
GenerateNewUniqueInt64 will take in old value and return new unique value with randomized seed and negated
func GenerateNewUniqueNullInt32 ¶
GenerateNewUniqueNullInt32 will take in old value and return new unique value with randomized seed and negated
func GenerateNewUniqueNullInt64 ¶
GenerateNewUniqueNullInt64 will take in old value and return new unique value with randomized seed and negated
func GenerateNewUniqueNullString ¶
func GenerateNewUniqueNullString(oldStrVal sql.NullString, stringLimit int) sql.NullString
GenerateNewUniqueNullString will take in old value and return new unique value with randomized seed
stringLimit = 0 no limit, > 0 has limit
func GenerateNewUniqueString ¶
GenerateNewUniqueString will take in old value and return new unique value with randomized seed
stringLimit = 0 no limit, > 0 has limit
func GenerateRandomChar ¶
func GenerateRandomChar() string
GenerateRandomChar will create a random character, using unix nano as seed
func GenerateRandomNumber ¶
GenerateRandomNumber with unix nano as seed
func GenerateULID ¶
GenerateULID will generate a ULID that is globally unique (very slim chance of collision)
func GenerateUUIDv4 ¶
GenerateUUIDv4 will generate a UUID Version 4 (Random) to represent a globally unique identifier (extremely rare chance of collision)
func GetDate ¶ added in v1.0.9
GetDate returns date based on given year month day, month max day is checked, leap year is checked
func GetFirstBoolOrDefault ¶
GetFirstBoolOrDefault will select the first variadic value from paramValue, if no paramValue variadic, then defaultValue is used as return value
func GetFirstByteOrDefault ¶
GetFirstByteOrDefault will select the first variadic value from paramValue, if no paramValue variadic, then defaultValue is used as return value
func GetFirstDateOfMonth ¶ added in v1.0.9
GetFirstDateOfMonth returns the given date's first date of month, for example, 8/21/2020 => 8/1/2020
func GetFirstFloat32OrDefault ¶
GetFirstFloat32OrDefault will select the first variadic value from paramValue, if no paramValue variadic, then defaultValue is used as return value
func GetFirstFloat64OrDefault ¶
GetFirstFloat64OrDefault will select the first variadic value from paramValue, if no paramValue variadic, then defaultValue is used as return value
func GetFirstInt64OrDefault ¶
GetFirstInt64OrDefault will select the first variadic value from paramValue, if no paramValue variadic, then defaultValue is used as return value
func GetFirstIntOrDefault ¶
GetFirstIntOrDefault will select the first variadic value from paramValue, if no paramValue variadic, then defaultValue is used as return value
func GetFirstOrDefault ¶
func GetFirstOrDefault(defaultValue interface{}, paramValue ...interface{}) interface{}
GetFirstOrDefault will select the first variadic value from paramValue, if no paramValue variadic, then defaultValue is used as return value
func GetFirstStringOrDefault ¶
GetFirstStringOrDefault will select the first variadic value from paramValue, if no paramValue variadic, then defaultValue is used as return value
func GetFirstTimeOrDefault ¶
GetFirstTimeOrDefault will select the first variadic value from paramValue, if no paramValue variadic, then defaultValue is used as return value
func GetLastDateOfMonth ¶ added in v1.0.9
GetLastDateOfMonth returns the given date's last day of the month, for example, 8/21/2020 => 8/31/2020
func GetNetListener ¶
GetNetListener triggers the specified port to listen via tcp
func GetStructTagValueByObject ¶
func GetStructTagValueByObject(structObj interface{}, structFieldName string, structTagName string) (notFound bool, tagValue string, t reflect.Type)
GetStructTagValueByObject will accept a struct object, struct field name, and struct tag name, and return the found tag value and reflect type, if reflect type or struct tag is not found, a notFound is returned [ Parameters ]
structObj = struct object variable structFieldName = struct's field name (CASE SENSITIVE) structTagName = struct's tag name (the left side of struct tag - the key portion) (CASE SENSITIVE)
func GetStructTagValueByType ¶
func GetStructTagValueByType(t reflect.Type, structFieldName string, structTagName string) (notFound bool, tagValue string)
GetStructTagValueByType will accept a prior obtained reflect type, struct field name, and struct tag name, and return the found tag value, if struct tag value is not found, a notFound is returned, if the reflect type is nil, then not found is returned too [ Parameters ]
t = reflect type of a struct object (obtained via GetStructTagValueByObject) structFieldName = struct's field name (CASE SENSITIVE) structTagName = struct's tag name (the left side of struct tag - the key portion) (CASE SENSITIVE)
func GetStructTagsValueSlice ¶ added in v1.1.1
func GetStructTagsValueSlice(field reflect.StructField, tagName ...string) (tagValues []string)
GetStructTagsValueSlice returns named struct tag values from field, in the order queried
func HTMLDecode ¶
HTMLDecode will unescape html tags and extended tags relevant to our apps
func HexToString ¶
HexToString converts hex data into string
func Int32PtrToInt ¶
Int32PtrToInt returns 0 if nil, otherwise actual int value.
func Int64PtrToInt64 ¶
Int64PtrToInt64 returns 0 if pointer is nil, otherwise actual int64 value.
func Int64ToString ¶
Int64ToString converts int64 into string value.
func Int64Val ¶ added in v1.1.1
Int64Val gets int64 value from int64 pointer, if pointer is nil, 0 is returned.
func IntSliceContains ¶ added in v1.0.9
IntSliceContains checks if value is contained within the intSlice
func IntVal ¶ added in v1.1.1
IntVal gets int value from int pointer. if pointer is nil, zero is returned.
func IsAlphanumericAndSpaceOnly ¶
IsAlphanumericAndSpaceOnly checks if the input string is A-Z, a-z, 0-9, and space
func IsAlphanumericOnly ¶
IsAlphanumericOnly checks if the input string is A-Z, a-z, and 0-9 only
func IsBase64Only ¶
IsBase64Only checks if the input string is a-z, A-Z, 0-9, +, /, =
func IsBoolType ¶ added in v1.1.1
IsBoolType tests if input string is boolean
func IsDateTimeValidYYMMDDhhmm ¶ added in v1.1.5
IsDateTimeValidYYMMDDhhmm checks if input string value is a valid date time represented in the format of YYMMDDhhmm (24 hour format)
func IsDateTimeValidYYMMDDhhmmss ¶ added in v1.1.5
IsDateTimeValidYYMMDDhhmmss checks if input string value is a valid date time represented in the format of YYMMDDhhmmss (24 hour format)
func IsDateTimeValidYYYYMMDDhhmm ¶ added in v1.1.5
IsDateTimeValidYYYYMMDDhhmm checks if input string value is a valid date time represented in the format of YYYYMMDDhhmm (24 hour format)
func IsDateTimeValidYYYYMMDDhhmmss ¶ added in v1.1.5
IsDateTimeValidYYYYMMDDhhmmss checks if input string value is a valid date time represented in the format of YYYYMMDDhhmmss (24 hour format)
func IsDateValidMMDDYY ¶ added in v1.1.5
IsDateValidMMDDYY checks if input string value is a valid date represented in the format of MMDDYY valid year detected is 1970 - 2099
func IsDateValidMMDDYYYY ¶ added in v1.1.5
IsDateValidMMDDYYYY checks if input string value is a valid date represented in the format of MMDDYYYY valid year detected is 1970 - 2099
func IsDateValidMMYY ¶ added in v1.1.5
IsDateValidMMYY checks if input string value is a valid date represented in the format of MMYY valid year detected is 00-99 with year 20xx assumed
func IsDateValidMMYYYY ¶ added in v1.1.5
IsDateValidMMYYYY checks if input string value is a valid date represented in the format of MMYYYY valid year detected is 1970 - 2099
func IsDateValidYYMM ¶ added in v1.1.5
IsDateValidYYMM checks if input string value is a valid date represented in the format of YYMM valid year detected is 00 - 99, with year 20xx assumed
func IsDateValidYYMMDD ¶ added in v1.1.5
IsDateValidYYMMDD checks if input string value is a valid date represented in the format of YYMMDD valid year detected is 00 - 99, with year 20xx assumed
func IsDateValidYYYYMM ¶ added in v1.1.5
IsDateValidYYYYMM checks if input string value is a valid date represented in the format of YYYYMM valid year detected is 1970 - 2099
func IsDateValidYYYYMMDD ¶ added in v1.1.5
IsDateValidYYYYMMDD checks if input string value is a valid date represented in the format of YYYYMMDD valid year detected is 1970 - 2099
func IsDayOfMonthValid ¶
IsDayOfMonthValid checks if the month day number is valid
func IsHttpsEndpoint ¶ added in v1.1.1
IsHttpsEndpoint returns true if url is https, false if otherwise
func IsLeapYear ¶
IsLeapYear checks if the year input is leap year or not
func IsNumericFloat64 ¶ added in v1.1.5
IsNumericFloat64 checks if string is float
func IsNumericIntAndNegativeSignOnly ¶
IsNumericIntAndNegativeSignOnly checks if the input string is 0-9 and possibly with lead negative sign only
func IsNumericIntOnly ¶
IsNumericIntOnly checks if the input string is 0-9 only
func IsStructFieldSet ¶ added in v1.1.1
func IsStructFieldSet(inputStructPtr interface{}) bool
IsStructFieldSet checks if any field value is not default blank or zero
func IsTimeValidhhmm ¶ added in v1.1.5
IsTimeValidhhmm checks if input string value is a valid time represented in the format of hhmm (24 hour format)
func IsTimeValidhhmmss ¶ added in v1.1.5
IsTimeValidhhmmss checks if input string value is a valid time represented in the format of hhmmss (24 hour format)
func ItoaZeroBlank ¶ added in v1.1.2
ItoaZeroBlank converts integer into string, if integer is zero, blank is returned.
func JsonFromEscaped ¶ added in v1.1.1
JsonFromEscaped will unescape the json data that may be special character escaped
func JsonToEscaped ¶ added in v1.1.1
JsonToEscaped will escape the data whose json special chars are escaped
func LenTrimNullString ¶
func LenTrimNullString(s sql.NullString) int
LenTrimNullString returns string length
func MarshalJSONCompact ¶
MarshalJSONCompact will accept an input variable, typically struct with json struct tags, to serialize from object into json string with compact formatting
*** STRUCT FIELDS MUST BE EXPORTED FOR MARSHAL AND UNMARSHAL ***
struct json tags:
`json:"ElementName"` <<< JSON Element Name `json:"...,omitempty"` <<< Omit This Line if Empty Value (false, 0, nil, zero length array) `json:"-"` <<< Omit From JSON Marshal
func MarshalJSONIndent ¶
MarshalJSONIndent will accept an input variable, typically struct with json struct tags, to serialize from object into json string with indented formatting
*** STRUCT FIELDS MUST BE EXPORTED FOR MARSHAL AND UNMARSHAL ***
struct json tags:
`json:"ElementName"` <<< JSON Element Name `json:"...,omitempty"` <<< Omit This Line if Empty Value (false, 0, nil, zero length array) `json:"-"` <<< Omit From JSON Marshal
func MarshalSliceStructToJson ¶ added in v1.1.1
func MarshalSliceStructToJson(inputSliceStructPtr []interface{}, tagName string, excludeTagName string) (jsonArrayOutput string, err error)
MarshalSliceStructToJson accepts a slice of struct pointer, then using tagName and excludeTagName to marshal to json array To pass in inputSliceStructPtr, convert slice of actual objects at the calling code, using SliceObjectsToSliceInterface(), if there is a need to name the value of tagName, but still need to exclude from output, use the excludeTagName with -, such as `x:"-"`
func MarshalStructToCSV ¶ added in v1.1.1
func MarshalStructToCSV(inputStructPtr interface{}, csvDelimiter string) (csvPayload string, err error)
MarshalStructToCSV will serialize struct fields defined with strug tags below, to csvPayload string (one line of csv data) using csvDelimiter, the csv payload ordinal position is based on the struct tag pos defined for each struct field, additionally processes struct tag data validation and length / range (if not valid, will set to data type default), this method provides data validation and if fails, will return error (for string if size exceeds max, it will truncate)
Predefined Struct Tags Usable:
- `pos:"1"` // ordinal position of the field in relation to the csv parsed output expected (Zero-Based Index) NOTE: if field is mutually exclusive with one or more uniqueId, then pos # should be named the same for all uniqueIds if multiple fields are in exclusive condition, and skipBlank or skipZero, always include a blank default field as the last of unique field list if value is '-', this means position value is calculated from other fields and set via `setter:"base.Xyz"` during unmarshal csv, there is no marshal to csv for this field
- `type:"xyz"` // data type expected: A = AlphabeticOnly, N = NumericOnly 0-9, AN = AlphaNumeric, ANS = AN + PrintableSymbols, H = Hex, B64 = Base64, B = true/false, REGEX = Regular Expression, Blank = Any,
- `regex:"xyz"` // if Type = REGEX, this struct tag contains the regular expression string, regex express such as [^A-Za-z0-9_-]+ method will replace any regex matched string to blank
- `size:"x..y"` // data type size rule: x = Exact size match x.. = From x and up ..y = From 0 up to y x..y = From x to y +%z = Append to x, x.., ..y, x..y; adds additional constraint that the result size must equate to 0 from modulo of z
- `range:"x..y"` // data type range value when Type is N, if underlying data type is string, method will convert first before testing
- `req:"true"` // indicates data value is required or not, true or false
- `getter:"Key"` // if field type is custom struct or enum, specify the custom method getter (no parameters allowed) that returns the expected value in first ordinal result position NOTE: if the method to invoke resides at struct level, precede the method name with 'base.', for example, 'base.XYZ' where XYZ is method name to invoke NOTE: if the method is to receive a parameter value, always in string data type, add '(x)' after the method name, such as 'XYZ(x)' or 'base.XYZ(x)'
- `setter:"ParseByKey` // if field type is custom struct or enum, specify the custom method (only 1 lookup parameter value allowed) setter that sets value(s) into the field NOTE: if the method to invoke resides at struct level, precede the method name with 'base.', for example, 'base.XYZ' where XYZ is method name to invoke NOTE: setter method always intake a string parameter value
- `booltrue:"1"` // if field is defined, contains bool literal for true condition, such as 1 or true, that overrides default system bool literal value, if bool literal value is determined by existence of outprefix and itself is blank, place a space in both booltrue and boolfalse (setting blank will negate literal override)
- `boolfalse:"0"` // if field is defined, contains bool literal for false condition, such as 0 or false, that overrides default system bool literal value if bool literal value is determined by existence of outprefix and itself is blank, place a space in both booltrue and boolfalse (setting blank will negate literal override)
- `uniqueid:"xyz"` // if two or more struct field is set with the same uniqueid, then only the first encountered field with the same uniqueid will be used in marshal, NOTE: if field is mutually exclusive with one or more uniqueId, then pos # should be named the same for all uniqueIds
- `skipblank:"false"` // if true, then any fields that is blank string will be excluded from marshal (this only affects fields that are string)
- `skipzero:"false"` // if true, then any fields that are 0, 0.00, time.Zero(), false, nil will be excluded from marshal (this only affects fields that are number, bool, time, pointer)
- `timeformat:"20060102"` // for time.Time field, optional date time format, specified as: 2006, 06 = year, 01, 1, Jan, January = month, 02, 2, _2 = day (_2 = width two, right justified) 03, 3, 15 = hour (15 = 24 hour format) 04, 4 = minute 05, 5 = second PM pm = AM PM
- `outprefix:""` // for marshal method, if field value is to precede with an output prefix, such as XYZ= (affects marshal queryParams / csv methods only) WARNING: if csv is variable elements count, rather than fixed count ordinal, then csv MUST include outprefix for all fields in order to properly identify target struct field
- `zeroblank:"false"` // set true to set blank to data when value is 0, 0.00, or time.IsZero
- `validate:"==x"` // if field has to match a specific value or the entire method call will fail, match data format as: ==xyz (== refers to equal, for numbers and string match, xyz is data to match, case insensitive) [if == validate against one or more values, use ||] !=xyz (!= refers to not equal) [if != validate against one or more values, use &&] >=xyz >>xyz <<xyz <=xyz (greater equal, greater, less than, less equal; xyz must be int or float) :=Xyz where Xyz is a parameterless function defined at struct level, that performs validation, returns bool or error where true or nil indicates validation success note: expected source data type for validate to be effective is string, int, float64; if field is blank and req = false, then validate will be skipped
func MarshalStructToJson ¶ added in v1.1.1
func MarshalStructToJson(inputStructPtr interface{}, tagName string, excludeTagName string) (string, error)
MarshalStructToJson marshals a struct pointer's fields to json string, output json names are based on values given in tagName, to exclude certain struct fields from being marshaled, include - as value in struct tag defined by tagName, if there is a need to name the value of tagName, but still need to exclude from output, use the excludeTagName with -, such as `x:"-"`
special struct tags:
- `getter:"Key"` // if field type is custom struct or enum, specify the custom method getter (no parameters allowed) that returns the expected value in first ordinal result position NOTE: if the method to invoke resides at struct level, precede the method name with 'base.', for example, 'base.XYZ' where XYZ is method name to invoke NOTE: if the method is to receive a parameter value, always in string data type, add '(x)' after the method name, such as 'XYZ(x)' or 'base.XYZ(x)'
- `booltrue:"1"` // if field is defined, contains bool literal for true condition, such as 1 or true, that overrides default system bool literal value if bool literal value is determined by existence of outprefix and itself is blank, place a space in both booltrue and boolfalse (setting blank will negate literal override)
- `boolfalse:"0"` // if field is defined, contains bool literal for false condition, such as 0 or false, that overrides default system bool literal value if bool literal value is determined by existence of outprefix and itself is blank, place a space in both booltrue and boolfalse (setting blank will negate literal override)
- `uniqueid:"xyz"` // if two or more struct field is set with the same uniqueid, then only the first encountered field with the same uniqueid will be used in marshal
- `skipblank:"false"` // if true, then any fields that is blank string will be excluded from marshal (this only affects fields that are string)
- `skipzero:"false"` // if true, then any fields that are 0, 0.00, time.Zero(), false, nil will be excluded from marshal (this only affects fields that are number, bool, time, pointer)
- `timeformat:"20060102"` // for time.Time field, optional date time format, specified as: 2006, 06 = year, 01, 1, Jan, January = month, 02, 2, _2 = day (_2 = width two, right justified) 03, 3, 15 = hour (15 = 24 hour format) 04, 4 = minute 05, 5 = second PM pm = AM PM
- `zeroblank:"false"` // set true to set blank to data when value is 0, 0.00, or time.IsZero
func MarshalStructToQueryParams ¶ added in v1.1.1
func MarshalStructToQueryParams(inputStructPtr interface{}, tagName string, excludeTagName string) (string, error)
MarshalStructToQueryParams marshals a struct pointer's fields to query params string, output query param names are based on values given in tagName, to exclude certain struct fields from being marshaled, use - as value in struct tag defined by tagName, if there is a need to name the value of tagName, but still need to exclude from output, use the excludeTagName with -, such as `x:"-"`
special struct tags:
- `getter:"Key"` // if field type is custom struct or enum, specify the custom method getter (no parameters allowed) that returns the expected value in first ordinal result position NOTE: if the method to invoke resides at struct level, precede the method name with 'base.', for example, 'base.XYZ' where XYZ is method name to invoke NOTE: if the method is to receive a parameter value, always in string data type, add '(x)' after the method name, such as 'XYZ(x)' or 'base.XYZ(x)'
- `booltrue:"1"` // if field is defined, contains bool literal for true condition, such as 1 or true, that overrides default system bool literal value, if bool literal value is determined by existence of outprefix and itself is blank, place a space in both booltrue and boolfalse (setting blank will negate literal override)
- `boolfalse:"0"` // if field is defined, contains bool literal for false condition, such as 0 or false, that overrides default system bool literal value if bool literal value is determined by existence of outprefix and itself is blank, place a space in both booltrue and boolfalse (setting blank will negate literal override)
- `uniqueid:"xyz"` // if two or more struct field is set with the same uniqueid, then only the first encountered field with the same uniqueid will be used in marshal
- `skipblank:"false"` // if true, then any fields that is blank string will be excluded from marshal (this only affects fields that are string)
- `skipzero:"false"` // if true, then any fields that are 0, 0.00, time.Zero(), false, nil will be excluded from marshal (this only affects fields that are number, bool, time, pointer)
- `timeformat:"20060102"` // for time.Time field, optional date time format, specified as: 2006, 06 = year, 01, 1, Jan, January = month, 02, 2, _2 = day (_2 = width two, right justified) 03, 3, 15 = hour (15 = 24 hour format) 04, 4 = minute 05, 5 = second PM pm = AM PM
- `outprefix:""` // for marshal method, if field value is to precede with an output prefix, such as XYZ= (affects marshal queryParams / csv methods only)
- `zeroblank:"false"` // set true to set blank to data when value is 0, 0.00, or time.IsZero
func MarshalXML ¶
MarshalXML with option for indent or compact
func MarshalXMLCompact ¶
MarshalXMLCompact will accept an input variable, typically struct with xml struct tags, to serialize from object into xml string
*** STRUCT FIELDS MUST BE EXPORTED FOR MARSHAL AND UNMARSHAL ***
special struct field:
XMLName xml.Name `xml:"ElementName"`
struct xml tags:
`xml:"AttributeName,attr"` or `xml:",attr"` <<< Attribute Instead of Element `xml:"ElementName"` <<< XML Element Name `xml:"OuterElementName>InnerElementName"` <<< Outer XML Grouping By OuterElementName `xml:",cdata"` <<< <![CDATA[...]] `xml:",innerxml"` <<< Write as Inner XML Verbatim and Not Subject to Marshaling `xml:",comment"` <<< Write as Comment, and Not Contain "--" Within Value `xml:"...,omitempty"` <<< Omit This Line if Empty Value (false, 0, nil, zero length array) `xml:"-"` <<< Omit From XML Marshal
func MarshalXMLIndent ¶
MarshalXMLIndent will accept an input variable, typically struct with xml struct tags, to serialize from object into xml string with indented formatting
*** STRUCT FIELDS MUST BE EXPORTED FOR MARSHAL AND UNMARSHAL ***
special struct field:
XMLName xml.Name `xml:"ElementName"`
struct xml tags:
`xml:"AttributeName,attr"` or `xml:",attr"` <<< Attribute Instead of Element `xml:"ElementName"` <<< XML Element Name `xml:"OuterElementName>InnerElementName"` <<< Outer XML Grouping By OuterElementName `xml:",cdata"` <<< <![CDATA[...]] `xml:",innerxml"` <<< Write as Inner XML Verbatim and Not Subject to Marshaling `xml:",comment"` <<< Write as Comment, and Not Contain "--" Within Value `xml:"...,omitempty"` <<< Omit This Line if Empty Value (false, 0, nil, zero length array) `xml:"-"` <<< Omit From XML Marshal
func Mid ¶
Mid returns the middle of string indicated by variable start and l positions (size of substring)
func MinutesDiff ¶
MinutesDiff gets the minutes difference between from and to date
func NewUUID ¶
func NewUUID() string
NewUUID will generate a UUID Version 4 (Random) and ignore error if any
func NextFixedLength ¶
NextFixedLength calculates the next fixed length total block size, for example, if block size is 16, then the total size should be 16, 32, 48 and so on based on data length
func ParseBool ¶
ParseBool tests and parses if input string is boolean, return value 1st bool is the boolean result, return value 2nd bool is the ParseBool success or failure indicator
func ParseDate ¶
ParseDate will parse a date value in yyyy-mm-dd format into time.Time object, check time.IsZero() to verify if a zero time is returned indicating parser failure
func ParseDateFromDDMMYYYY ¶
ParseDateFromDDMMYYYY from string value
func ParseDateFromMMDD ¶
ParseDateFromMMDD from string value
func ParseDateFromMMYY ¶
ParseDateFromMMYY from string value
func ParseDateFromYYMM ¶
ParseDateFromYYMM from string value
func ParseDateFromYYMMDD ¶
ParseDateFromYYMMDD from string value
func ParseDateFromYYYYMMDD ¶
ParseDateFromYYYYMMDD from string value
func ParseDateTime ¶
ParseDateTime will parse a date time value in yyyy-mm-dd hh:mm:ss tt format into time.Time object, check time.IsZero() to verify if a zero time is returned indicating parser failure
func ParseDateTime24Hr ¶
ParseDateTime24Hr will parse a date time value in yyyy-mm-dd HH:mm:ss format into time.Time object, check time.IsZero() to verify if a zero time is returned indicating parser failure
func ParseDateTimeCustom ¶
ParseDateTimeCustom will parse a date time value in s string, based on the f format f format is 2006 01 02 15:04:05 / 03:04:05 PM
func ParseDateTimeFromMMDDYYYYhhmmss ¶
ParseDateTimeFromMMDDYYYYhhmmss from string value
func ParseDateTimeFromYYYYMMDDhhmmss ¶
ParseDateTimeFromYYYYMMDDhhmmss from string value
func ParseDateToLastDayOfMonth ¶
ParseDateToLastDayOfMonth takes in a time.Time struct and returns the last date of month
func ParseEmvTlvTagNamesOnly ¶ added in v1.1.2
ParseEmvTlvTagNamesOnly accepts a hex payload of emv tlv names string, performs parsing of emv tags (2 and 4 digit hex as found in getEmvTags()), the expected emvTlvTagsPayload is tag hex names appended one after another, without delimiters, no other tag values in the string
Reference Info:
EMVLab Emv Tag Search = http://www.emvlab.org/emvtags/ EMVLab Emv Tags Decode Sample = http://www.emvlab.org/tlvutils/?data=6F2F840E325041592E5359532E4444463031A51DBF0C1A61184F07A0000000031010500A564953412044454249548701019000 Hex To String Decoder = http://www.convertstring.com/EncodeDecode/HexDecode --- Stack Overflow Article = https://stackoverflow.com/questions/36740699/decode-emv-tlv-data Stack Overflow Article = https://stackoverflow.com/questions/15059580/reading-emv-card-using-ppse-and-not-pse/19593841#19593841
func ParseFloat32 ¶
ParseFloat32 tests and parses if input string is float 32 bit (decimal point value)
func ParseFloat64 ¶
ParseFloat64 tests and parses if input string is float 64 bit (decimal point value)
func ParseFromExcelDate ¶ added in v1.0.9
ParseFromExcelDate will handle integer value of excel date to convert to time.Time
func ParseHostFromURL ¶
ParseHostFromURL will parse out the host name from url
func ParseHttpHeader ¶ added in v1.1.4
ParseHttpHeader parses headers into map[string]string, where slice of header values for a key is delimited with semi-colon (;)
func ParseInt32 ¶
ParseInt32 tests and parses if input string is integer (whole numbers 32 bits)
func ParseInt64 ¶
ParseInt64 tests and parses if input string is big integer (whole number greater 64 bits)
func ParseKeyValue ¶
ParseKeyValue will parse the input string using specified delimiter (= is default), result is set in the key and val fields
func ParseTime ¶
ParseTime will parse a time vaule in hh:mm:ss tt format into time.Time object, check time.IsZero() to verify if a zero time is returned indicating parser failure
func ParseTimeFromhhmmss ¶ added in v1.1.5
ParseTimeFromhhmmss will parse a time value from hhmmss format into time.Time object, if parse failed, time.Time{} is returned (use time.IsZero() to check if parse success)
func ReadHttpRequestBody ¶ added in v1.1.4
ReadHttpRequestBody reads raw body from http request body object, and then sets the read body back to the request (once reading will remove the body content if not restored)
func ReadHttpRequestHeaders ¶ added in v1.1.4
ReadHttpRequestHeaders parses headers into map
func ReflectCall ¶ added in v1.1.1
func ReflectCall(o reflect.Value, methodName string, paramValue ...interface{}) (resultSlice []reflect.Value, notFound bool)
ReflectCall uses reflection to invoke a method by name, and pass in param values if any, result is returned via reflect.Value object slice
func ReflectGetType ¶ added in v1.1.7
ReflectGetType returns the type of obj interface{} passed in. if obj interface{} is a pointer, then its base type will be returned instead
func ReflectObjectNewPtr ¶ added in v1.1.7
ReflectObjectNewPtr creates a new object ptr for the object type given at parameter. the return interface{} represents the actual object ptr created
func ReflectStringToField ¶ added in v1.1.1
ReflectStringToField accepts string value and reflects into reflect.Value field based on the field data type
timeFormat:
2006, 06 = year, 01, 1, Jan, January = month, 02, 2, _2 = day (_2 = width two, right justified) 03, 3, 15 = hour (15 = 24 hour format) 04, 4 = minute 05, 5 = second PM pm = AM PM
func ReflectTypeRegistryAdd ¶ added in v1.1.1
ReflectTypeRegistryAdd will accept a custom struct object, and add its type into custom type registry, if customFullTypeName is not specified, the type name is inferred from the type itself, custom type registry is used by reflect unmarshal helpers to construct custom type for undefined interface targets
func ReflectTypeRegistryCount ¶ added in v1.1.1
func ReflectTypeRegistryCount() int
ReflectTypeRegistryCount returns count of custom types registered in the type registry
func ReflectTypeRegistryGet ¶ added in v1.1.1
ReflectTypeRegistryGet returns a previously registered custom type in the type registry, based on the given type name string
func ReflectTypeRegistryRemove ¶ added in v1.1.1
func ReflectTypeRegistryRemove(customFullTypeName string)
ReflectTypeRegistryRemove will remove a pre-registered custom type from type registry for the given type name
func ReflectTypeRegistryRemoveAll ¶ added in v1.1.1
func ReflectTypeRegistryRemoveAll()
ReflectTypeRegistryRemoveAll will clear all previously registered custom types from type registry
func ReflectValueToString ¶ added in v1.1.1
func ReflectValueToString(o reflect.Value, boolTrue string, boolFalse string, skipBlank bool, skipZero bool, timeFormat string, zeroBlank bool) (valueStr string, skip bool, err error)
ReflectValueToString accepts reflect.Value and returns its underlying field value in string data type boolTrue is the literal value to use for bool true condition, boolFalse is the false condition literal, if boolTrue or boolFalse is not defined, then default 'true' or 'false' is used, skipBlank and skipZero if true indicates if field value is blank (string) or Zero (int, float, time, pointer, bool) then skip render, zeroBlank = will blank the value if it is 0, 0.00, or time.IsZero
timeFormat:
2006, 06 = year, 01, 1, Jan, January = month, 02, 2, _2 = day (_2 = width two, right justified) 03, 3, 15 = hour (15 = 24 hour format) 04, 4 = minute 05, 5 = second PM pm = AM PM
func RegexReplaceSubString ¶
func RegexReplaceSubString(source string, subStringFrom string, subStringTo string, replaceWith string, caseInsensitive bool) string
RegexReplaceSubString will search for substring between subStringFrom and subStringTo, replace with the replaceWith string, and optionally case insensitive or not
func RightTrimLF ¶
RightTrimLF will remove linefeed (return char) from the right most char and return result string
func SecondsDiff ¶
SecondsDiff gets the seconds difference between from and to date
func SetStructFieldDefaultValues ¶ added in v1.1.1
func SetStructFieldDefaultValues(inputStructPtr interface{}) bool
SetStructFieldDefaultValues sets default value defined in struct tag `def:""` into given field, this method is used during unmarshal action only, default value setting is for value types and fields with `setter:""` defined only, time format is used if field is datetime, for overriding default format of ISO style
func SliceDeleteElement ¶ added in v1.1.1
func SliceDeleteElement(slice interface{}, removalIndex int) (resultSlice interface{})
SliceDeleteElement accepts slice (value type or pointer type, primitive or complex struct), removes element by index position removalIndex, and returns the reassembled result slice without the removed element
note: this method does not preserve element ordering, this is in order to achieve faster call performance
removalIndex = positive number indicates element removal index position (0-based index)
negative number indicates element removal index from right, -1 = last element to remove; -2 = second to the last to remove, and so on positive / negative number out of bound = returns original slice unchanged
if resultSlice is nil, then no slice remain
func SliceObjectsToSliceInterface ¶
func SliceObjectsToSliceInterface(objectsSlice interface{}) (output []interface{})
SliceObjectsToSliceInterface converts slice of objects into slice of interfaces. objectsSlice is received via interface parameter, and is expected to be a Slice, the slice is enumerated to convert each object within the slice to interface{}, the final converted slice of interface is returned, if operation failed, nil is returned.
func SliceSeekElement ¶ added in v1.0.9
func SliceSeekElement(slice []interface{}, filterFunc func(input interface{}, filter ...interface{}) bool, filterParam ...interface{}) interface{}
SliceSeekElement returns the first filterFunc input object's true response note: use SliceObjectToSliceInterface to convert slice of objects to slice of interface before passing to slice parameter
func SliceStringToCSVString ¶ added in v1.0.9
SliceStringToCSVString unboxes slice of string into comma separated string
func SplitString ¶
SplitString will split the source string using delimiter, and return the element indicated by index, if nothing is found, blank is returned, index = -1 returns last index
func StrToUint ¶
StrToUint converts from string to uint, if string is not a valid uint, 0 is returned.
func StrToUint64 ¶ added in v1.1.1
StrToUint64 converts from string to uint64, if string is not a valid uint64, 0 is returned.
func StringPtrToString ¶
StringPtrToString gets string value from string pointer, if pointer is nil, blank string is returned.
func StringSliceContains ¶ added in v1.0.9
StringSliceContains checks if value is contained within the strSlice
func StringSliceExtractUnique ¶ added in v1.1.5
StringSliceExtractUnique returns unique string slice elements
func StringVal ¶ added in v1.1.1
StringVal gets string value from string pointer, if pointer is nil, blank string is returned.
func StructClearFields ¶ added in v1.1.1
func StructClearFields(inputStructPtr interface{})
StructClearFields will clear all fields within struct with default value
func StructNonDefaultRequiredFieldsCount ¶ added in v1.2.0
func StructNonDefaultRequiredFieldsCount(inputStructPtr interface{}) int
StructNonDefaultRequiredFieldsCount returns count of struct fields that are tagged as required but not having any default values pre-set
func TimeFormatString ¶
func TimeFormatString() string
TimeFormatString returns the time format string constant (hh:mm:ss tt)
func TimeVal ¶ added in v1.1.1
TimeVal gets Time struct from Time pointer, if pointer is nil, a time.Time{} is returned.
func ToNullFloat32 ¶
func ToNullFloat32(d float32, emptyAsNull bool) sql.NullFloat64
ToNullFloat32 sets float32 into NullFloat64 output
func ToNullFloat64 ¶
func ToNullFloat64(d float64, emptyAsNull bool) sql.NullFloat64
ToNullFloat64 sets float64 into NullFloat64 output
func ToNullInt64 ¶
ToNullInt64 sets int64 value into NullInt64 output
func ToNullString ¶
func ToNullString(s string, emptyAsNull bool) sql.NullString
ToNullString sets string value into NullString output
func ToNullTime ¶
ToNullTime sets time.Time into NullTime output
func UInt64ToString ¶
UInt64ToString converts uint64 value to string.
func UintVal ¶ added in v1.1.1
UintVal gets uint value from uint pointer, if uint pointer is nil, 0 is returned.
func UnmarshalCSVToStruct ¶ added in v1.1.1
func UnmarshalCSVToStruct(inputStructPtr interface{}, csvPayload string, csvDelimiter string, customDelimiterParserFunc func(string) []string) error
UnmarshalCSVToStruct will parse csvPayload string (one line of csv data) using csvDelimiter, (if csvDelimiter = "", then customDelimiterParserFunc is required) and set parsed csv element value into struct fields based on Ordinal Position defined via struct tag, additionally processes struct tag data validation and length / range (if not valid, will set to data type default)
Predefined Struct Tags Usable:
- `pos:"1"` // ordinal position of the field in relation to the csv parsed output expected (Zero-Based Index) NOTE: if field is mutually exclusive with one or more uniqueId, then pos # should be named the same for all uniqueIds, if multiple fields are in exclusive condition, and skipBlank or skipZero, always include a blank default field as the last of unique field list if value is '-', this means position value is calculated from other fields and set via `setter:"base.Xyz"` during unmarshal csv, there is no marshal to csv for this field
- `type:"xyz"` // data type expected: A = AlphabeticOnly, N = NumericOnly 0-9, AN = AlphaNumeric, ANS = AN + PrintableSymbols, H = Hex, B64 = Base64, B = true/false, REGEX = Regular Expression, Blank = Any,
- `regex:"xyz"` // if Type = REGEX, this struct tag contains the regular expression string, regex express such as [^A-Za-z0-9_-]+ method will replace any regex matched string to blank
- `size:"x..y"` // data type size rule: x = Exact size match x.. = From x and up ..y = From 0 up to y x..y = From x to y +%z = Append to x, x.., ..y, x..y; adds additional constraint that the result size must equate to 0 from modulo of z
- `range:"x..y"` // data type range value when Type is N, if underlying data type is string, method will convert first before testing
- `req:"true"` // indicates data value is required or not, true or false
- `getter:"Key"` // if field type is custom struct or enum, specify the custom method getter (no parameters allowed) that returns the expected value in first ordinal result position NOTE: if the method to invoke resides at struct level, precede the method name with 'base.', for example, 'base.XYZ' where XYZ is method name to invoke NOTE: if the method is to receive a parameter value, always in string data type, add '(x)' after the method name, such as 'XYZ(x)' or 'base.XYZ(x)'
- `setter:"ParseByKey` // if field type is custom struct or enum, specify the custom method (only 1 lookup parameter value allowed) setter that sets value(s) into the field NOTE: if the method to invoke resides at struct level, precede the method name with 'base.', for example, 'base.XYZ' where XYZ is method name to invoke NOTE: setter method always intake a string parameter value
- `outprefix:""` // for marshal method, if field value is to precede with an output prefix, such as XYZ= (affects marshal queryParams / csv methods only) WARNING: if csv is variable elements count, rather than fixed count ordinal, then csv MUST include outprefix for all fields in order to properly identify target struct field
- `def:""` // default value to set into struct field in case unmarshal doesn't set the struct field value
- `timeformat:"20060102"` // for time.Time field, optional date time format, specified as: 2006, 06 = year, 01, 1, Jan, January = month, 02, 2, _2 = day (_2 = width two, right justified) 03, 3, 15 = hour (15 = 24 hour format) 04, 4 = minute 05, 5 = second PM pm = AM PM
- `booltrue:"1"` // if field is defined, contains bool literal for true condition, such as 1 or true, that overrides default system bool literal value, if bool literal value is determined by existence of outprefix and itself is blank, place a space in both booltrue and boolfalse (setting blank will negate literal override)
- `boolfalse:"0"` // if field is defined, contains bool literal for false condition, such as 0 or false, that overrides default system bool literal value if bool literal value is determined by existence of outprefix and itself is blank, place a space in both booltrue and boolfalse (setting blank will negate literal override)
- `validate:"==x"` // if field has to match a specific value or the entire method call will fail, match data format as: ==xyz (== refers to equal, for numbers and string match, xyz is data to match, case insensitive) [if == validate against one or more values, use ||] !=xyz (!= refers to not equal) [if != validate against one or more values, use &&] >=xyz >>xyz <<xyz <=xyz (greater equal, greater, less than, less equal; xyz must be int or float) :=Xyz where Xyz is a parameterless function defined at struct level, that performs validation, returns bool or error where true or nil indicates validation success note: expected source data type for validate to be effective is string, int, float64; if field is blank and req = false, then validate will be skipped
func UnmarshalJSON ¶
UnmarshalJSON will accept input json data string and deserialize into target object indicated by parameter v
*** PASS PARAMETER AS "&v" IN ORDER TO BE WRITABLE *** *** v interface{} MUST BE initialized first *** *** STRUCT FIELDS MUST BE EXPORTED FOR MARSHAL AND UNMARSHAL ***
if unmarshal is successful, nil is returned, otherwise error info is returned
func UnmarshalJsonToStruct ¶ added in v1.1.1
func UnmarshalJsonToStruct(inputStructPtr interface{}, jsonPayload string, tagName string, excludeTagName string) error
UnmarshalJsonToStruct will parse jsonPayload string, and set parsed json element value into struct fields based on struct tag named by tagName, any tagName value with - will be ignored, any excludeTagName defined with value of - will also cause parser to ignore the field
note: this method expects simple json in key value pairs only, not json containing slices or more complex json structs within existing json field
Predefined Struct Tags Usable:
- `setter:"ParseByKey` // if field type is custom struct or enum, specify the custom method (only 1 lookup parameter value allowed) setter that sets value(s) into the field NOTE: if the method to invoke resides at struct level, precede the method name with 'base.', for example, 'base.XYZ' where XYZ is method name to invoke NOTE: setter method always intake a string parameter
- `def:""` // default value to set into struct field in case unmarshal doesn't set the struct field value
- `timeformat:"20060102"` // for time.Time field, optional date time format, specified as: 2006, 06 = year, 01, 1, Jan, January = month, 02, 2, _2 = day (_2 = width two, right justified) 03, 3, 15 = hour (15 = 24 hour format) 04, 4 = minute 05, 5 = second PM pm = AM PM
- `booltrue:"1"` // if field is defined, contains bool literal for true condition, such as 1 or true, that overrides default system bool literal value, if bool literal value is determined by existence of outprefix and itself is blank, place a space in both booltrue and boolfalse (setting blank will negate literal override)
- `boolfalse:"0"` // if field is defined, contains bool literal for false condition, such as 0 or false, that overrides default system bool literal value if bool literal value is determined by existence of outprefix and itself is blank, place a space in both booltrue and boolfalse (setting blank will negate literal override)
func UnmarshalXML ¶
UnmarshalXML will accept input xml data string and deserialize into target object indicated by parameter v
*** PASS PARAMETER AS "&v" IN ORDER TO BE WRITABLE ***
*** STRUCT FIELDS MUST BE EXPORTED FOR MARSHAL AND UNMARSHAL ***
if unmarshal is successful, nil is returned, otherwise error info is returned
func VerifyGoogleReCAPTCHAv2 ¶ added in v1.1.1
func VerifyGoogleReCAPTCHAv2(response string, secret string) (success bool, challengeTs time.Time, hostName string, err error)
VerifyGoogleReCAPTCHAv2 will verify recaptcha v2 response data against given secret and obtain a response from google server
func XMLFromEscaped ¶
XMLFromEscaped will un-escape the data whose > < & % ' " are converted to > < & % ' "
func XMLToEscaped ¶
XMLToEscaped will escape the data whose xml special chars > < & % ' " are escaped into > < & % ' "
Types ¶
type EmvTlvTag ¶ added in v1.1.2
type EmvTlvTag struct { TagName string TagHexValueCount int TagHexValue string TagDecodedValue string }
func ParseEmvTlvTags ¶ added in v1.1.2
ParseEmvTlvTags accepts a hex payload of emv tlv data string, performs parsing of emv tags (2 and 4 digit hex as found in getEmvTags()), the expected emvTlvTagsPayload is tag hex + tag value len in hex + tag value in hex, data is composed without any other delimiters
Reference Info:
EMVLab Emv Tag Search = http://www.emvlab.org/emvtags/ EMVLab Emv Tags Decode Sample = http://www.emvlab.org/tlvutils/?data=6F2F840E325041592E5359532E4444463031A51DBF0C1A61184F07A0000000031010500A564953412044454249548701019000 Hex To String Decoder = http://www.convertstring.com/EncodeDecode/HexDecode --- Stack Overflow Article = https://stackoverflow.com/questions/36740699/decode-emv-tlv-data Stack Overflow Article = https://stackoverflow.com/questions/15059580/reading-emv-card-using-ppse-and-not-pse/19593841#19593841
func ParseEncryptedTlvTags ¶ added in v1.1.2
ParseEncryptedTlvTags accepts a hex payload of encrypted tlv data string, performs parsing of emv tags (2, 4 and 6 digit hex as found in getEncryptedTlvTags()), the expected encryptedTlvTagsPayload is tag hex + tag value len in hex + tag value in hex, data is composed without any other delimiters
Reference Info:
EMVLab Emv Tag Search = http://www.emvlab.org/emvtags/ EMVLab Emv Tags Decode Sample = http://www.emvlab.org/tlvutils/?data=6F2F840E325041592E5359532E4444463031A51DBF0C1A61184F07A0000000031010500A564953412044454249548701019000 Hex To String Decoder = http://www.convertstring.com/EncodeDecode/HexDecode --- Stack Overflow Article = https://stackoverflow.com/questions/36740699/decode-emv-tlv-data Stack Overflow Article = https://stackoverflow.com/questions/15059580/reading-emv-card-using-ppse-and-not-pse/19593841#19593841
type JsonTime ¶ added in v1.1.6
JsonTime provides custom Json marshal and unmarshal interface implementations. JsonTime marshals and unmarshal using RFC3339 time format
func ToJsonTime ¶ added in v1.1.6
ToJsonTime converts time.Time to JsonTime
func ToJsonTimePtr ¶ added in v1.1.6
ToJsonTimePtr converts time.Time to JsonTime pointer
func (*JsonTime) MarshalJSON ¶ added in v1.1.6
MarshalJSON marshals time value to format of RFC3339
func (*JsonTime) UnmarshalJSON ¶ added in v1.1.6
UnmarshalJSON unmarshal time value in format of RFC3339 to JsonTime