# README
common
Common helper utilities and wrappers for code reuse.
When we code projects, we constantly encounter a similar set of functionality and logic. This package's intent is to wrap those commonly recurring functionalities and access points into a reusable helper package, so that we don't have to keep maintaining separate code bases.
This package will continue to be updated with more reusable code as well.
Usage
- To use the common package:
- in the project folder root:
- go mod init
- go mod tidy
- For example, if project is "HelloWorld":
- /HelloWorld/go mod init
- /HelloWorld/go mod tidy
types of helpers
- string helpers
- number helpers
- io helpers
- converter helpers
- db type helpers
- net helpers
- reflection helpers
- regex helpers
- time and date helpers
- uuid helpers
- crypto helpers (aes, gcm, rsa, sha, etc)
- csv parser helpers
- wrappers for aws related services
- service discovery / cloud map wrapper (using aws sdk)
- dynamodb / dax wrapper (using aws sdk)
- kms wrapper (using aws sdk)
- redis wrapper (using go-redis package)
- s3 wrapper (using aws sdk)
- ses wrapper (using aws sdk)
- sqs wrapper (using aws sdk)
- sns wrapper (using aws sdk)
- gin web server
- xray wrapper (using aws sdk)
- use xray.Init() to config
- use xray.SetXRayServiceOn() to enable xray tracing
- xray tracing is already coded into the following services:
- kms, cloudmap, dynamodb, redis, s3, ses, sns, sqs, mysql, gin
- wrappers for relational database access
- mysql wrapper (using sqlx package)
- sqlite wrapper (using sqlx package)
- sqlserver wrapper (using sqlx package)
- other wrappers
- for running as systemd service
- for logging and config
- for circuit breaker and rate limit
- etc.
build and deploy automation
- Create a file such as 'build.sh' within project
- Edit file content as:
#!/bin/zsh
GOOS=linux GOARCH=amd64 go build
scp -i ~/.ssh/YourKey.pem YourBinary hostUserName@hostIP:/home/hostUserName/targetFolder
- Descriptions:
- YourKey.pem = the Linux Host SSH Certificate Key
- YourBinary = the Binary Build by go build to Upload
- hostUserName = the Linux Host Login Username
- hostIP = the Linux Host IP Address
- hostUserName = the Linux Host Login Username
- targetFolder = the Linux Host Folder Where SCP Will Upload YourBinary To
# Functions
AbsDuration returns absolute value of d.
AbsFloat64 returns absolute value of f.
AbsInt returns absolute value of i.
AbsInt64 returns absolute value of i.
Atob converts string to bool.
Atoi converts string to integer.
Base64StdDecode will decode given data from base 64 standard encoded string.
Base64StdEncode will encode given data into base 64 standard encoded string.
Base64UrlDecode will decode given data from base 64 url encoded string.
Base64UrlEncode will encode given data into base 64 url encoded string.
BoolPtr converts bool value to bool pointer.
BoolPtrToBool converts bool pointer to bool value.
BoolToInt converts bool to int value, true = 1, false = 0.
BoolToString converts bool to string value, true = "true", false = "false".
BoolVal gets bool value from bool pointer, if pointer is nil, false is returned.
Btoa converts bool to string, true = "true", false = "false".
ByteToHex converts byte array into hex.
CentsToFloat64 converts int (cents) into float64 value with two decimal value.
ConsolePromptAndAnswer is a helper to prompt a message and then scan a response in console.
ConsolePromptAndAnswerBool is a helper to prompt a message and then scan a response in console.
ConsolePromptAndAnswerFloat64 is a helper to prompt a message and then scan a response in console.
ConsolePromptAndAnswerInt is a helper to prompt a message and then scan a response in console.
ConvertStructToSlice converts a struct passed as an interface{} to a slice of that struct's type.
CopyDir - Dir copies a whole directory recursively.
CopyFile - File copies a single file from src to dst.
CurrentDate returns current date in yyyy-mm-dd format.
CurrentDateStruct returns current date in yyyy-mm-dd format via time.Time struct.
CurrentDateTime returns current date and time in yyyy-mm-dd hh:mm:ss tt format.
CurrentDateTimeStruct returns current date and time in yyyy-mm-dd hh:mm:ss tt format via time.Time struct.
CurrentTime returns current time in hh:mm:ss tt format.
DateAfter checks if testDate is after the afterDate.
DateAfterOrEqual checks if testDate is after or equal to the afterEqualDate.
DateBefore checks if testDate is before the beforeDate.
DateBeforeOrEqual checks if testDate is before or equal to the beforeEqualDate.
DateBetween checks if testDate is within the fromDate and toDate, if doNotIncludeEqual = true, then testDate equals fromDate and toDate are skipped.
DateEqual checks if the testDate equals to the equalDate.
DateFormatString returns the date format string constant (yyyy-mm-dd).
DateOutside checks if the testDate is outside of the fromDate and toDate.
DatePtrToString formats pointer time.Time to string date format yyyy-mm-dd.
DateTimeFormatString returns the date time format string constant (yyyy-mm-dd hh:mm:ss tt).
DateTimePtrToDateTime formats pointer time.Time to time.Time struct.
DateTimePtrToString formats pointer time.Time to string date time format yyyy-mm-dd hh:mm:ss AM/PM.
DateToLocal converts given time to local time.
DateToLocal2 returns local value directly without error info.
DateToUTC converts given time to utc.
DateToUTC2 returns utc value directly without error info.
DaysDiff gets the days difference between from and to date.
DerefError dereferences reflect.Value to error object if underlying type was error.
DerefPointersZero gets pointer base type.
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.
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.
DurationPtr casts Duration to Duration pointer.
DurationVal gets Duration value from Duration pointer, if pointer is nil, 0 is returned.
EncodeHttpHeaderMapToString converts header map[string]string to string representation.
No description provided by the author
No description provided by the author
ErrorMessage find the error cause time, file, code line number and error message.
ExponentialToNumber converts exponential representation of a number into actual number equivalent.
ExtractAlpha will extract A-Z out of string to be returned.
ExtractAlphaNumeric will extract only A-Z, a-z, and 0-9 out of string to be returned.
ExtractAlphaNumericPrintableSymbols will extra A-Z, a-z, 0-9, and printable symbols.
ExtractAlphaNumericUnderscoreDash will extract only A-Z, a-z, 0-9, _, - out of string to be returned.
ExtractByRegex will extract string based on regex expression, any regex match will be replaced with blank.
ExtractHex will extract only A-F, a-f, and 0-9 out of string to be returned.
ExtractNumeric will extract only 0-9 out of string to be returned.
FileExists checks if input file in path exists.
FileRead will read all file content of given file in path, return as string if successful, if failed, error will contain the error reason.
FileReadBytes will read all file content and return slice of byte.
FileWrite will write data into file at the given path, if successful, no error is returned (nil).
FileWriteBytes will write byte data into file at the given path, if successful, no error is returned (nil).
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.
Float32Ptr gets float32 pointer from float32 value.
Float32PtrToFloat32 returns 0 if pointer is nil, otherwise actual float32 value.
Float32ToString converts float32 value to string.
Float32ToStringCents converts float32 value into string representing cent values, 2.12 returned as "212".
Float64Ptr gets float64 pointer from float64 value.
Float64PtrToFloat64 returns 0 if nil, otherwise actual float64 value.
Float64ToInt converts from float64 into int, if conversion fails, 0 is returned.
Float64ToIntCents converts float64 value into int, representing cent values, 2.12 returned as 212.
Float64ToString converts float64 value into string value.
Float64Val gets float64 value from float64 pointer, if pointer is nil, 0 is returned.
FloatToString converts float64 value into string value.
FormatDate will format the input date value to yyyy-mm-dd.
FormatDateTime will format the input date value to yyyy-mm-dd hh:mm:ss tt.
FormatDateTimeToISO8601_RFC3339 accepts time struct and converts to iso8601 string output format.
FormatDateTimeToMMDDYYYYhhmmss for the date time struct received.
FormatDateTimeToYYYYMMDDhhmmss for the date time struct received.
FormatDateToDDMMYYYY for the date time struct received.
FormatDateToMMDD for the date time struct received.
FormatDateToMMYY for the date time struct received.
FormatDateToYYMM for the date time struct received.
FormatDateToYYMMDD for the date time struct received.
FormatDateToYYYYMMDD for the date time struct received.
FormatTime will format the input date value to hh:mm:ss tt.
FormatTimeTohhmmss for the date time struct received.
FromNullBool casts sql null bool variable to bool variable, if null, false is returned.
FromNullFloat32 casts sql null float64 into float32 variable.
FromNullFloat64 casts sql null float64 variable to float64 variable, if null, 0.00 is returned.
FromNullInt casts sql NullInt32 into int variable, if null, 0 is returned.
FromNullInt64 casts sql null int64 variable to int64 variable, if null, 0 is returned.
FromNullString casts sql null string variable to string variable, if null, blank string is returned.
FromNullTime parses string into time.Time.
GenerateNewUniqueInt32 will take in old value and return new unique value with randomized seed and negated.
GenerateNewUniqueInt64 will take in old value and return new unique value with randomized seed and negated.
GenerateNewUniqueNullInt32 will take in old value and return new unique value with randomized seed and negated.
GenerateNewUniqueNullInt64 will take in old value and return new unique value with randomized seed and negated.
GenerateNewUniqueNullString will take in old value and return new unique value with randomized seed
stringLimit = 0 no limit, > 0 has limit.
GenerateNewUniqueString will take in old value and return new unique value with randomized seed
stringLimit = 0 no limit, > 0 has limit.
GenerateRandomChar will create a random character, using unix nano as seed.
GenerateRandomNumber with unix nano as seed.
GenerateULID will generate a ULID that is globally unique (very slim chance of collision).
GenerateUUIDv4 will generate a UUID Version 4 (Random) to represent a globally unique identifier (extremely rare chance of collision).
GetDate returns date based on given year month day, month max day is checked, leap year is checked.
GetFirstBoolOrDefault will select the first variadic value from paramValue, if no paramValue variadic, then defaultValue is used as return value.
GetFirstByteOrDefault will select the first variadic value from paramValue, if no paramValue variadic, then defaultValue is used as return value.
GetFirstDateOfMonth returns the given date's first date of month, for example, 8/21/2020 => 8/1/2020.
GetFirstFloat32OrDefault will select the first variadic value from paramValue, if no paramValue variadic, then defaultValue is used as return value.
GetFirstFloat64OrDefault will select the first variadic value from paramValue, if no paramValue variadic, then defaultValue is used as return value.
GetFirstInt64OrDefault will select the first variadic value from paramValue, if no paramValue variadic, then defaultValue is used as return value.
GetFirstIntOrDefault will select the first variadic value from paramValue, if no paramValue variadic, then defaultValue is used as return value.
GetFirstOrDefault will select the first variadic value from paramValue, if no paramValue variadic, then defaultValue is used as return value.
GetFirstStringOrDefault will select the first variadic value from paramValue, if no paramValue variadic, then defaultValue is used as return value.
GetFirstTimeOrDefault will select the first variadic value from paramValue, if no paramValue variadic, then defaultValue is used as return value.
GetLastDateOfMonth returns the given date's last day of the month, for example, 8/21/2020 => 8/31/2020.
GetLocalIP returns the first non loopback ip.
GetNetListener triggers the specified port to listen via tcp.
GetStructFieldTagAndValues extracts values of a specific struct tag and their corresponding field values from the given struct object.
GetStructFieldValue retrieves the value of a specific field from a struct.
GetStructTagsValueSlice returns named struct tag values from field, in the order queried.
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).
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).
GetULIDTimestamp will return the timestamp of the ulid string.
HexToByte converts hex data into byte array.
HexToString converts hex data into string.
HoursDiff gets the hours difference between from and to date.
HTMLDecode will unescape html tags and extended tags relevant to our apps.
HTMLEncode will escape html tags.
Int32PtrToInt returns 0 if nil, otherwise actual int value.
Int64Ptr gets int64 pointer from int64 value.
Int64PtrToInt64 returns 0 if pointer is nil, otherwise actual int64 value.
Int64ToString converts int64 into string value.
Int64Val gets int64 value from int64 pointer, if pointer is nil, 0 is returned.
IntPtr int pointer from int value.
IntSliceContains checks if value is contained within the intSlice.
IntToHex returns HEX string representation of i, in 2 digit blocks.
IntVal gets int value from int pointer.
IsAlphanumericAndSpaceOnly checks if the input string is A-Z, a-z, 0-9, and space.
IsAlphanumericOnly checks if the input string is A-Z, a-z, and 0-9 only.
IsBase64Only checks if the input string is a-z, A-Z, 0-9, +, /, =.
IsBoolType tests if input string is boolean.
IsDateTimeValid_ISO8601_RFC3339 checks if input string value is a valid date time represented in the format of ISO8601 RFC3339 date time.
IsDateTimeValidYYMMDDhhmm checks if input string value is a valid date time represented in the format of YYMMDDhhmm (24 hour format).
IsDateTimeValidYYMMDDhhmmss checks if input string value is a valid date time represented in the format of YYMMDDhhmmss (24 hour format).
IsDateTimeValidYYYYMMDDhhmm checks if input string value is a valid date time represented in the format of YYYYMMDDhhmm (24 hour format).
IsDateTimeValidYYYYMMDDhhmmss checks if input string value is a valid date time represented in the format of YYYYMMDDhhmmss (24 hour format).
IsDateValidMMDDYY checks if input string value is a valid date represented in the format of MMDDYY valid year detected is 1970 - 2099.
IsDateValidMMDDYYYY checks if input string value is a valid date represented in the format of MMDDYYYY valid year detected is 1970 - 2099.
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.
IsDateValidMMYYYY checks if input string value is a valid date represented in the format of MMYYYY valid year detected is 1970 - 2099.
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.
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.
IsDateValidYYYYMM checks if input string value is a valid date represented in the format of YYYYMM valid year detected is 1970 - 2099.
IsDateValidYYYYMMDD checks if input string value is a valid date represented in the format of YYYYMMDD valid year detected is 1970 - 2099.
IsDayOfMonthValid checks if the month day number is valid.
IsFloat32 tests if input string is float 32 bit (decimal point value).
IsFloat64 tests if input string is float 64 bit (decimal point value).
IsHexOnly checks if the input string is a-f, A-F, 0-9.
IsHttpsEndpoint returns true if url is https, false if otherwise.
IsInt32 tests if input string is integer (whole numbers 32 bits).
IsInt64 tests if input string is big integer (whole number greater 64 bits).
IsLeapYear checks if the year input is leap year or not.
IsNumericFloat64 checks if string is float.
IsNumericIntAndNegativeSignOnly checks if the input string is 0-9 and possibly with lead negative sign only.
IsNumericIntOnly checks if the input string is 0-9 only.
IsStructFieldSet checks if any field value is not default blank or zero.
IsTimeValidhhmm checks if input string value is a valid time represented in the format of hhmm (24 hour format).
IsTimeValidhhmmss checks if input string value is a valid time represented in the format of hhmmss (24 hour format).
IsULIDValid will check if the ulid string is valid.
Itoa converts integer into string.
ItoaZeroBlank converts integer into string, if integer is zero, blank is returned.
JsonFromEscaped will unescape the json data that may be special character escaped.
JsonToEscaped will escape the data whose json special chars are escaped.
Left returns the left side of string indicated by variable l (size of substring).
LenTrim returns length of space trimmed string s.
LenTrimNullString returns string length.
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.
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.
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:"-"`.
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: 1.
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: 1.
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: 1.
MarshalXML with option for indent or compact.
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.
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.
Mid returns the middle of string indicated by variable start and l positions (size of substring).
MinutesDiff gets the minutes difference between from and to date.
NewULID will generate a new ULID and ignore error if any.
NewUUID will generate a UUID Version 4 (Random) and ignore error if any.
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.
Padding will pad the data with specified char either to the left or right.
PadLeft will pad data with space to the left.
PadRight will pad data with space to the right.
PadX pads X to the left by default.
PadZero pads zero to the left by default.
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.
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.
ParseDateFromDDMMYYYY from string value.
ParseDateFromMMDD from string value.
ParseDateFromMMYY from string value.
ParseDateFromYYMM from string value.
ParseDateFromYYMMDD from string value.
ParseDateFromYYYYMMDD from string value.
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.
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.
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.
ParseDateTimeFrom_ISO8601_RFC3339 from string value of RFC3339 date time format.
ParseDateTimeFromMMDDYYYYhhmmss from string value.
ParseDateTimeFromYYYYMMDDhhmmss from string value.
ParseDateToLastDayOfMonth takes in a time.Time struct and returns the last date of month.
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.
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.
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.
ParseFloat32 tests and parses if input string is float 32 bit (decimal point value).
ParseFloat64 tests and parses if input string is float 64 bit (decimal point value).
ParseFromExcelDate will handle integer value of excel date to convert to time.Time.
ParseHostFromURL will parse out the host name from url.
ParseHttpHeader parses headers into map[string]string, where slice of header values for a key is delimited with semi-colon (;).
ParseInt32 tests and parses if input string is integer (whole numbers 32 bits).
ParseInt64 tests and parses if input string is big integer (whole number greater 64 bits).
ParseKeyValue will parse the input string using specified delimiter (= is default), result is set in the key and val fields.
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.
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).
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).
ReadHttpRequestHeaders parses headers into map.
ReflectAppendSlices appends two slices provided as interface{} and returns the resulting slice.
ReflectCall uses reflection to invoke a method by name, and pass in param values if any, result is returned via reflect.Value object slice.
ReflectGetType returns the type of obj interface{} passed in.
ReflectInterfaceToString converts interface{} to string.
ReflectObjectNewPtr creates a new object ptr for the object type given at parameter.
ReflectSetStringSliceToField sets a slice of strings to a specified field in a struct passed as an interface{}.
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.
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.
ReflectTypeRegistryCount returns count of custom types registered in the type registry.
ReflectTypeRegistryGet returns a previously registered custom type in the type registry, based on the given type name string.
ReflectTypeRegistryRemove will remove a pre-registered custom type from type registry for the given type name.
ReflectTypeRegistryRemoveAll will clear all previously registered custom types from type registry.
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.
RegexReplaceSubString will search for substring between subStringFrom and subStringTo, replace with the replaceWith string, and optionally case insensitive or not.
Replace will replace old char with new char and return the replaced string.
Reverse a string.
Right returns the right side of string indicated by variable l (size of substring).
RightTrimLF will remove linefeed (return char) from the right most char and return result string.
RoundFloat64 converts float64 value to target precision.
RoundIntegerToNearestBlock returns conformed block size value where val fall into.
SecondsDiff gets the seconds difference between from and to date.
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.
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.
SliceObjectsToSliceInterface converts slice of objects into slice of interfaces.
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.
SliceStringToCSVString unboxes slice of string into comma separated string.
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.
StringPtr gets string pointer from string value.
StringPtrToString gets string value from string pointer, if pointer is nil, blank string is returned.
StringSliceContains checks if value is contained within the strSlice.
StringSliceExtractUnique returns unique string slice elements.
StringToHex converts string into hex.
StringVal gets string value from string pointer, if pointer is nil, blank string is returned.
StrToInt64 converts from string to int64, if string is not a valid int64, 0 is returned.
StrToUint converts from string to uint, if string is not a valid uint, 0 is returned.
StrToUint64 converts from string to uint64, if string is not a valid uint64, 0 is returned.
StructClearFields will clear all fields within struct with default value.
StructNonDefaultRequiredFieldsCount returns count of struct fields that are tagged as required but not having any default values pre-set.
TimeFormatString returns the time format string constant (hh:mm:ss tt).
TimePtr casts Time struct to Time pointer.
TimeVal gets Time struct from Time pointer, if pointer is nil, a time.Time{} is returned.
ToJsonTime converts time.Time to JsonTime.
ToJsonTimePtr converts time.Time to JsonTime pointer.
ToNullBool sets bool into NullBool output.
ToNullFloat32 sets float32 into NullFloat64 output.
ToNullFloat64 sets float64 into NullFloat64 output.
ToNullInt sets int value into NullInt32 output.
ToNullInt64 sets int64 value into NullInt64 output.
ToNullString sets string value into NullString output.
ToNullTime sets time.Time into NullTime output.
Trim gets the left and right space trimmed input string s.
UInt64ToString converts uint64 value to string.
UintPtr gets uint pointer from uint value.
UintToStr converts from uint to string.
UintVal gets uint value from uint pointer, if uint pointer is nil, 0 is returned.
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: 1.
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.
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: 1.
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.
VerifyGoogleReCAPTCHAv2 will verify recaptcha v2 response data against given secret and obtain a response from google server.
XMLFromEscaped will un-escape the data whose > < & % ' " are converted to > < & % ' ".
XMLToEscaped will escape the data whose xml special chars > < & % ' " are escaped into > < & % ' ".
# Structs
No description provided by the author
No description provided by the author
# Type aliases
JsonTime provides custom Json marshal and unmarshal interface implementations.