helper

package module
v1.3.7 Latest Latest
Warning

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

Go to latest
Published: Nov 18, 2023 License: Apache-2.0 Imports: 29 Imported by: 22

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

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

Constants

This section is empty.

Variables

This section is empty.

Functions

func AbsDuration added in v1.1.2

func AbsDuration(d time.Duration) time.Duration

AbsDuration returns absolute value of d

func AbsFloat64 added in v1.0.9

func AbsFloat64(f float64) float64

AbsFloat64 returns absolute value of f

func AbsInt added in v1.0.9

func AbsInt(i int) int

AbsInt returns absolute value of i

func AbsInt64 added in v1.1.2

func AbsInt64(i int64) int64

AbsInt64 returns absolute value of i

func Atob

func Atob(s string) bool

Atob converts string to bool. string values with first char lower cased "t", "y", "1" treated as true, otherwise false.

func Atoi

func Atoi(s string) int

Atoi converts string to integer.

func Base64StdDecode

func Base64StdDecode(data string) (string, error)

Base64StdDecode will decode given data from base 64 standard encoded string

func Base64StdEncode

func Base64StdEncode(data string) string

Base64StdEncode will encode given data into base 64 standard encoded string

func Base64UrlDecode

func Base64UrlDecode(data string) (string, error)

Base64UrlDecode will decode given data from base 64 url encoded string

func Base64UrlEncode

func Base64UrlEncode(data string) string

Base64UrlEncode will encode given data into base 64 url encoded string

func BoolPtr added in v1.0.9

func BoolPtr(b bool) *bool

BoolPtr converts bool value to bool pointer.

func BoolPtrToBool

func BoolPtrToBool(b *bool) bool

BoolPtrToBool converts bool pointer to bool value.

func BoolToInt

func BoolToInt(b bool) int

BoolToInt converts bool to int value, true = 1, false = 0.

func BoolToString added in v1.1.1

func BoolToString(b bool) string

BoolToString converts bool to string value, true = "true", false = "false".

func BoolVal added in v1.1.1

func BoolVal(b *bool) bool

BoolVal gets bool value from bool pointer, if pointer is nil, false is returned.

func Btoa

func Btoa(b bool) string

Btoa converts bool to string, true = "true", false = "false".

func ByteToHex

func ByteToHex(data []byte) string

ByteToHex converts byte array into hex

func CentsToFloat64 added in v1.1.4

func CentsToFloat64(i int) float64

CentsToFloat64 converts int (cents) into float64 value with two decimal value.

func ConsolePromptAndAnswer added in v1.0.9

func ConsolePromptAndAnswer(prompt string, replyLowercase bool, autoTrim ...bool) string

ConsolePromptAndAnswer is a helper to prompt a message and then scan a response in console

func ConsolePromptAndAnswerBool added in v1.0.9

func ConsolePromptAndAnswerBool(prompt string, defaultTrue ...bool) bool

ConsolePromptAndAnswerBool is a helper to prompt a message and then scan a response in console

func ConsolePromptAndAnswerFloat64 added in v1.0.9

func ConsolePromptAndAnswerFloat64(prompt string, preventNegative ...bool) float64

ConsolePromptAndAnswerFloat64 is a helper to prompt a message and then scan a response in console

func ConsolePromptAndAnswerInt added in v1.0.9

func ConsolePromptAndAnswerInt(prompt string, preventNegative ...bool) int

ConsolePromptAndAnswerInt is a helper to prompt a message and then scan a response in console

func CopyDir

func CopyDir(src string, dst string) error

CopyDir - Dir copies a whole directory recursively

func CopyFile

func CopyFile(src string, dst string) error

CopyFile - File copies a single file from src to dst

func CurrentDate

func CurrentDate() string

CurrentDate returns current date in yyyy-mm-dd format

func CurrentDateStruct

func CurrentDateStruct() time.Time

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

func CurrentDateTimeStruct() time.Time

CurrentDateTimeStruct returns current date and time in yyyy-mm-dd hh:mm:ss tt format via time.Time struct

func CurrentTime

func CurrentTime() string

CurrentTime returns current time in hh:mm:ss tt format

func DateAfter

func DateAfter(testDate time.Time, afterDate time.Time) bool

DateAfter checks if testDate is after the afterDate

func DateAfterOrEqual

func DateAfterOrEqual(testDate time.Time, afterEqualDate time.Time) bool

DateAfterOrEqual checks if testDate is after or equal to the afterEqualDate

func DateBefore

func DateBefore(testDate time.Time, beforeDate time.Time) bool

DateBefore checks if testDate is before the beforeDate

func DateBeforeOrEqual

func DateBeforeOrEqual(testDate time.Time, beforeEqualDate time.Time) bool

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 DateEqual

func DateEqual(testDate time.Time, equalDate time.Time) bool

DateEqual checks if the testDate equals to the equalDate

func DateFormatString

func DateFormatString() string

DateFormatString returns the date format string constant (yyyy-mm-dd)

func DateOutside

func DateOutside(testDate time.Time, fromDate time.Time, toDate time.Time) bool

DateOutside checks if the testDate is outside of the fromDate and toDate

func DatePtrToString

func DatePtrToString(t *time.Time) string

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

func DateTimePtrToDateTime(t *time.Time) time.Time

DateTimePtrToDateTime formats pointer time.Time to time.Time struct.

func DateTimePtrToString

func DateTimePtrToString(t *time.Time) string

DateTimePtrToString formats pointer time.Time to string date time format yyyy-mm-dd hh:mm:ss AM/PM.

func DateToLocal

func DateToLocal(t time.Time) (time.Time, error)

DateToLocal converts given time to local time

func DateToLocal2

func DateToLocal2(t time.Time) time.Time

DateToLocal2 returns local value directly without error info

func DateToUTC

func DateToUTC(t time.Time) (time.Time, error)

DateToUTC converts given time to utc

func DateToUTC2

func DateToUTC2(t time.Time) time.Time

DateToUTC2 returns utc value directly without error info

func DaysDiff

func DaysDiff(timeFrom time.Time, timeTo time.Time) int

DaysDiff gets the days difference between from and to date

func DerefError added in v1.1.1

func DerefError(v reflect.Value) error

DerefError dereferences reflect.Value to error object if underlying type was error

func DerefPointersZero added in v1.1.1

func DerefPointersZero(rv reflect.Value) (drv reflect.Value, isPtr bool, isNilPtr bool)

DerefPointersZero gets pointer base type

func DnsLookupIps

func DnsLookupIps(host string) (ipList []net.IP)

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

func DnsLookupSrvs(host string) (ipList []string)

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

func DurationPtr(d time.Duration) *time.Duration

DurationPtr casts Duration to Duration pointer.

func DurationVal added in v1.1.1

func DurationVal(d *time.Duration) time.Duration

DurationVal gets Duration value from Duration pointer, if pointer is nil, 0 is returned.

func EncodeHttpHeaderMapToString added in v1.1.4

func EncodeHttpHeaderMapToString(headerMap map[string]string) string

EncodeHttpHeaderMapToString converts header map[string]string to string representation

func ErrAddLineTimeFileInfo added in v1.3.5

func ErrAddLineTimeFileInfo(err error) error

func ErrNewAddLineTimeFileInfo added in v1.3.5

func ErrNewAddLineTimeFileInfo(msg string) error

func ErrorMessage added in v1.3.3

func ErrorMessage(err error) string

ErrorMessage find the error cause time, file, code line number and error message

func ExponentialToNumber added in v1.0.9

func ExponentialToNumber(exp string) string

ExponentialToNumber converts exponential representation of a number into actual number equivalent

func ExtractAlpha added in v1.1.1

func ExtractAlpha(s string) (string, error)

ExtractAlpha will extract A-Z out of string to be returned

func ExtractAlphaNumeric

func ExtractAlphaNumeric(s string) (string, error)

ExtractAlphaNumeric will extract only A-Z, a-z, and 0-9 out of string to be returned

func ExtractAlphaNumericPrintableSymbols added in v1.1.1

func ExtractAlphaNumericPrintableSymbols(s string) (string, error)

ExtractAlphaNumericPrintableSymbols will extra A-Z, a-z, 0-9, and printable symbols

func ExtractAlphaNumericUnderscoreDash added in v1.1.1

func ExtractAlphaNumericUnderscoreDash(s string) (string, error)

ExtractAlphaNumericUnderscoreDash will extract only A-Z, a-z, 0-9, _, - out of string to be returned

func ExtractByRegex added in v1.1.1

func ExtractByRegex(s string, regexStr string) (string, error)

ExtractByRegex will extract string based on regex expression, any regex match will be replaced with blank

func ExtractHex added in v1.1.2

func ExtractHex(s string) (string, error)

ExtractHex will extract only A-F, a-f, and 0-9 out of string to be returned

func ExtractNumeric

func ExtractNumeric(s string) (string, error)

ExtractNumeric will extract only 0-9 out of string to be returned

func FileExists

func FileExists(path string) bool

FileExists checks if input file in path exists

func FileRead

func FileRead(path string) (string, error)

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

func FileReadBytes(path string) ([]byte, error)

FileReadBytes will read all file content and return slice of byte

func FileWrite

func FileWrite(path string, data string) error

FileWrite will write data into file at the given path, if successful, no error is returned (nil)

func FileWriteBytes added in v1.0.9

func FileWriteBytes(path string, data []byte) error

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

func Float32Ptr(f float32) *float32

Float32Ptr gets float32 pointer from float32 value.

func Float32PtrToFloat32

func Float32PtrToFloat32(f *float32) float32

Float32PtrToFloat32 returns 0 if pointer is nil, otherwise actual float32 value.

func Float32ToString

func Float32ToString(f float32) string

Float32ToString converts float32 value to string.

func Float32ToStringCents

func Float32ToStringCents(f float32) string

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

func Float64Ptr(f float64) *float64

Float64Ptr gets float64 pointer from float64 value.

func Float64PtrToFloat64

func Float64PtrToFloat64(f *float64) float64

Float64PtrToFloat64 returns 0 if nil, otherwise actual float64 value.

func Float64ToInt

func Float64ToInt(f float64) int

Float64ToInt converts from float64 into int, if conversion fails, 0 is returned.

func Float64ToIntCents added in v1.1.2

func Float64ToIntCents(f float64) int

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

func Float64ToString(f float64) string

Float64ToString converts float64 value into string value.

func Float64Val added in v1.1.1

func Float64Val(f *float64) float64

Float64Val gets float64 value from float64 pointer, if pointer is nil, 0 is returned.

func FloatToString

func FloatToString(f float64) string

FloatToString converts float64 value into string value.

func FormatDate

func FormatDate(t time.Time, blankIfZero ...bool) string

FormatDate will format the input date value to yyyy-mm-dd

func FormatDateTime

func FormatDateTime(t time.Time, blankIfZero ...bool) string

FormatDateTime will format the input date value to yyyy-mm-dd hh:mm:ss tt

func FormatDateTimeToISO8601_RFC3339 added in v1.2.7

func FormatDateTimeToISO8601_RFC3339(t time.Time, blankIfZero ...bool) string

FormatDateTimeToISO8601_RFC3339 accepts time struct and converts to iso8601 string output format

func FormatDateTimeToMMDDYYYYhhmmss

func FormatDateTimeToMMDDYYYYhhmmss(t time.Time) string

FormatDateTimeToMMDDYYYYhhmmss for the date time struct received

func FormatDateTimeToYYYYMMDDhhmmss

func FormatDateTimeToYYYYMMDDhhmmss(t time.Time) string

FormatDateTimeToYYYYMMDDhhmmss for the date time struct received

func FormatDateToDDMMYYYY

func FormatDateToDDMMYYYY(t time.Time) string

FormatDateToDDMMYYYY for the date time struct received

func FormatDateToMMDD

func FormatDateToMMDD(t time.Time) string

FormatDateToMMDD for the date time struct received

func FormatDateToMMYY

func FormatDateToMMYY(t time.Time) string

FormatDateToMMYY for the date time struct received

func FormatDateToYYMM

func FormatDateToYYMM(t time.Time) string

FormatDateToYYMM for the date time struct received

func FormatDateToYYMMDD

func FormatDateToYYMMDD(t time.Time) string

FormatDateToYYMMDD for the date time struct received

func FormatDateToYYYYMMDD

func FormatDateToYYYYMMDD(t time.Time) string

FormatDateToYYYYMMDD for the date time struct received

func FormatTime

func FormatTime(t time.Time, blankIfZero ...bool) string

FormatTime will format the input date value to hh:mm:ss tt

func FormatTimeTohhmmss added in v1.1.5

func FormatTimeTohhmmss(t time.Time) string

FormatTimeTohhmmss for the date time struct received

func FromNullBool

func FromNullBool(b sql.NullBool) bool

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

func FromNullInt(d sql.NullInt32) int

FromNullInt casts sql NullInt32 into int variable, if null, 0 is returned

func FromNullInt64

func FromNullInt64(d sql.NullInt64) int64

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

func FromNullTime(t sql.NullTime) time.Time

FromNullTime parses string into time.Time

func GenerateNewUniqueInt32

func GenerateNewUniqueInt32(oldIntVal int) int

GenerateNewUniqueInt32 will take in old value and return new unique value with randomized seed and negated

func GenerateNewUniqueInt64

func GenerateNewUniqueInt64(oldIntVal int64) int64

GenerateNewUniqueInt64 will take in old value and return new unique value with randomized seed and negated

func GenerateNewUniqueNullInt32

func GenerateNewUniqueNullInt32(oldIntVal sql.NullInt32) sql.NullInt32

GenerateNewUniqueNullInt32 will take in old value and return new unique value with randomized seed and negated

func GenerateNewUniqueNullInt64

func GenerateNewUniqueNullInt64(oldIntVal sql.NullInt64) sql.NullInt64

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

func GenerateNewUniqueString(oldStrVal string, stringLimit int) string

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

func GenerateRandomNumber(maxNumber int) int

GenerateRandomNumber with unix nano as seed

func GenerateULID

func GenerateULID() (string, error)

GenerateULID will generate a ULID that is globally unique (very slim chance of collision)

func GenerateUUIDv4

func GenerateUUIDv4() (string, error)

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

func GetDate(year int, month int, day int) time.Time

GetDate returns date based on given year month day, month max day is checked, leap year is checked

func GetFirstBoolOrDefault

func GetFirstBoolOrDefault(defaultValue bool, paramValue ...bool) bool

GetFirstBoolOrDefault will select the first variadic value from paramValue, if no paramValue variadic, then defaultValue is used as return value

func GetFirstByteOrDefault

func GetFirstByteOrDefault(defaultValue byte, paramValue ...byte) byte

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

func GetFirstDateOfMonth(t time.Time) time.Time

GetFirstDateOfMonth returns the given date's first date of month, for example, 8/21/2020 => 8/1/2020

func GetFirstFloat32OrDefault

func GetFirstFloat32OrDefault(defaultValue float32, paramValue ...float32) float32

GetFirstFloat32OrDefault will select the first variadic value from paramValue, if no paramValue variadic, then defaultValue is used as return value

func GetFirstFloat64OrDefault

func GetFirstFloat64OrDefault(defaultValue float64, paramValue ...float64) float64

GetFirstFloat64OrDefault will select the first variadic value from paramValue, if no paramValue variadic, then defaultValue is used as return value

func GetFirstInt64OrDefault

func GetFirstInt64OrDefault(defaultValue int64, paramValue ...int64) int64

GetFirstInt64OrDefault will select the first variadic value from paramValue, if no paramValue variadic, then defaultValue is used as return value

func GetFirstIntOrDefault

func GetFirstIntOrDefault(defaultValue int, paramValue ...int) int

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

func GetFirstStringOrDefault(defaultValue string, paramValue ...string) string

GetFirstStringOrDefault will select the first variadic value from paramValue, if no paramValue variadic, then defaultValue is used as return value

func GetFirstTimeOrDefault

func GetFirstTimeOrDefault(defaultValue time.Time, paramValue ...time.Time) time.Time

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

func GetLastDateOfMonth(t time.Time) time.Time

GetLastDateOfMonth returns the given date's last day of the month, for example, 8/21/2020 => 8/31/2020

func GetLocalIP

func GetLocalIP() string

GetLocalIP returns the first non loopback ip

func GetNetListener

func GetNetListener(port uint) (net.Listener, error)

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

func HTMLDecode(s string) string

HTMLDecode will unescape html tags and extended tags relevant to our apps

func HTMLEncode

func HTMLEncode(s string) string

HTMLEncode will escape html tags

func HexToByte

func HexToByte(hexData string) ([]byte, error)

HexToByte converts hex data into byte array

func HexToString

func HexToString(hexData string) (string, error)

HexToString converts hex data into string

func HoursDiff

func HoursDiff(timeFrom time.Time, timeTo time.Time) int

HoursDiff gets the hours difference between from and to date

func Int32PtrToInt

func Int32PtrToInt(n *int) int

Int32PtrToInt returns 0 if nil, otherwise actual int value.

func Int64Ptr

func Int64Ptr(i int64) *int64

Int64Ptr gets int64 pointer from int64 value.

func Int64PtrToInt64

func Int64PtrToInt64(n *int64) int64

Int64PtrToInt64 returns 0 if pointer is nil, otherwise actual int64 value.

func Int64ToString

func Int64ToString(n int64) string

Int64ToString converts int64 into string value.

func Int64Val added in v1.1.1

func Int64Val(i *int64) int64

Int64Val gets int64 value from int64 pointer, if pointer is nil, 0 is returned.

func IntPtr

func IntPtr(i int) *int

IntPtr int pointer from int value.

func IntSliceContains added in v1.0.9

func IntSliceContains(intSlice *[]int, value int) bool

IntSliceContains checks if value is contained within the intSlice

func IntToHex added in v1.1.1

func IntToHex(i int) string

IntToHex returns HEX string representation of i, in 2 digit blocks.

func IntVal added in v1.1.1

func IntVal(i *int) int

IntVal gets int value from int pointer. if pointer is nil, zero is returned.

func IsAlphanumericAndSpaceOnly

func IsAlphanumericAndSpaceOnly(s string) bool

IsAlphanumericAndSpaceOnly checks if the input string is A-Z, a-z, 0-9, and space

func IsAlphanumericOnly

func IsAlphanumericOnly(s string) bool

IsAlphanumericOnly checks if the input string is A-Z, a-z, and 0-9 only

func IsBase64Only

func IsBase64Only(s string) bool

IsBase64Only checks if the input string is a-z, A-Z, 0-9, +, /, =

func IsBoolType added in v1.1.1

func IsBoolType(s string) bool

IsBoolType tests if input string is boolean

func IsDateTimeValidYYMMDDhhmm added in v1.1.5

func IsDateTimeValidYYMMDDhhmm(s string) bool

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

func IsDateTimeValidYYMMDDhhmmss(s string) bool

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

func IsDateTimeValidYYYYMMDDhhmm(s string) bool

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

func IsDateTimeValidYYYYMMDDhhmmss(s string) bool

IsDateTimeValidYYYYMMDDhhmmss checks if input string value is a valid date time represented in the format of YYYYMMDDhhmmss (24 hour format)

func IsDateTimeValid_ISO8601_RFC3339 added in v1.3.4

func IsDateTimeValid_ISO8601_RFC3339(s string) bool

IsDateTimeValid_ISO8601_RFC3339 checks if input string value is a valid date time represented in the format of ISO8601 RFC3339 date time

func IsDateValidMMDDYY added in v1.1.5

func IsDateValidMMDDYY(s string) bool

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

func IsDateValidMMDDYYYY(s string) bool

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

func IsDateValidMMYY(s string) bool

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

func IsDateValidMMYYYY(s string) bool

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

func IsDateValidYYMM(s string) bool

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

func IsDateValidYYMMDD(s string) bool

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

func IsDateValidYYYYMM(s string) bool

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

func IsDateValidYYYYMMDD(s string) bool

IsDateValidYYYYMMDD checks if input string value is a valid date represented in the format of YYYYMMDD valid year detected is 1970 - 2099

func IsDayOfMonthValid

func IsDayOfMonthValid(year int, month int, day int) bool

IsDayOfMonthValid checks if the month day number is valid

func IsFloat32

func IsFloat32(s string) bool

IsFloat32 tests if input string is float 32 bit (decimal point value)

func IsFloat64

func IsFloat64(s string) bool

IsFloat64 tests if input string is float 64 bit (decimal point value)

func IsHexOnly

func IsHexOnly(s string) bool

IsHexOnly checks if the input string is a-f, A-F, 0-9

func IsHttpsEndpoint added in v1.1.1

func IsHttpsEndpoint(url string) bool

IsHttpsEndpoint returns true if url is https, false if otherwise

func IsInt32

func IsInt32(s string) bool

IsInt32 tests if input string is integer (whole numbers 32 bits)

func IsInt64

func IsInt64(s string) bool

IsInt64 tests if input string is big integer (whole number greater 64 bits)

func IsLeapYear

func IsLeapYear(year int) bool

IsLeapYear checks if the year input is leap year or not

func IsNumericFloat64 added in v1.1.5

func IsNumericFloat64(s string, positiveOnly bool) bool

IsNumericFloat64 checks if string is float

func IsNumericIntAndNegativeSignOnly

func IsNumericIntAndNegativeSignOnly(s string) bool

IsNumericIntAndNegativeSignOnly checks if the input string is 0-9 and possibly with lead negative sign only

func IsNumericIntOnly

func IsNumericIntOnly(s string) bool

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

func IsTimeValidhhmm(s string) bool

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

func IsTimeValidhhmmss(s string) bool

IsTimeValidhhmmss checks if input string value is a valid time represented in the format of hhmmss (24 hour format)

func Itoa

func Itoa(i int) string

Itoa converts integer into string.

func ItoaZeroBlank added in v1.1.2

func ItoaZeroBlank(i int) string

ItoaZeroBlank converts integer into string, if integer is zero, blank is returned.

func JsonFromEscaped added in v1.1.1

func JsonFromEscaped(data string) string

JsonFromEscaped will unescape the json data that may be special character escaped

func JsonToEscaped added in v1.1.1

func JsonToEscaped(data string) string

JsonToEscaped will escape the data whose json special chars are escaped

func Left

func Left(s string, l int) string

Left returns the left side of string indicated by variable l (size of substring)

func LenTrim

func LenTrim(s string) int

LenTrim returns length of space trimmed string s

func LenTrimNullString

func LenTrimNullString(s sql.NullString) int

LenTrimNullString returns string length

func MarshalJSONCompact

func MarshalJSONCompact(v interface{}) (string, error)

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

func MarshalJSONIndent(v interface{}) (string, error)

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:

  1. `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
  2. `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,
  3. `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
  4. `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
  5. `range:"x..y"` // data type range value when Type is N, if underlying data type is string, method will convert first before testing
  6. `req:"true"` // indicates data value is required or not, true or false
  7. `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)'
  8. `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
  9. `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)
  10. `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)
  11. `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
  12. `skipblank:"false"` // if true, then any fields that is blank string will be excluded from marshal (this only affects fields that are string)
  13. `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)
  14. `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
  15. `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
  16. `zeroblank:"false"` // set true to set blank to data when value is 0, 0.00, or time.IsZero
  17. `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:

  1. `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)'
  2. `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)
  3. `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)
  4. `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
  5. `skipblank:"false"` // if true, then any fields that is blank string will be excluded from marshal (this only affects fields that are string)
  6. `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)
  7. `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
  8. `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:

  1. `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)'
  2. `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)
  3. `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)
  4. `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
  5. `skipblank:"false"` // if true, then any fields that is blank string will be excluded from marshal (this only affects fields that are string)
  6. `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)
  7. `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
  8. `outprefix:""` // for marshal method, if field value is to precede with an output prefix, such as XYZ= (affects marshal queryParams / csv methods only)
  9. `zeroblank:"false"` // set true to set blank to data when value is 0, 0.00, or time.IsZero

func MarshalXML

func MarshalXML(v interface{}, indentXML bool) (string, error)

MarshalXML with option for indent or compact

func MarshalXMLCompact

func MarshalXMLCompact(v interface{}) (string, error)

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

func MarshalXMLIndent(v interface{}) (string, error)

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

func Mid(s string, start int, l int) string

Mid returns the middle of string indicated by variable start and l positions (size of substring)

func MinutesDiff

func MinutesDiff(timeFrom time.Time, timeTo time.Time) int

MinutesDiff gets the minutes difference between from and to date

func NewULID

func NewULID() string

NewULID will generate a new ULID and ignore error if any

func NewUUID

func NewUUID() string

NewUUID will generate a UUID Version 4 (Random) and ignore error if any

func NextFixedLength

func NextFixedLength(data string, blockSize int) int

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 PadLeft

func PadLeft(data string, totalSize int) string

PadLeft will pad data with space to the left

func PadRight

func PadRight(data string, totalSize int) string

PadRight will pad data with space to the right

func PadX added in v1.0.9

func PadX(data string, totalSize int, padRight ...bool) string

PadX pads X to the left by default

func PadZero added in v1.0.9

func PadZero(data string, totalSize int, padRight ...bool) string

PadZero pads zero to the left by default

func Padding

func Padding(data string, totalSize int, padRight bool, padChar string) string

Padding will pad the data with specified char either to the left or right

func ParseBool

func ParseBool(s string) (bool, bool)

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

func ParseDate(s string) time.Time

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

func ParseDateFromDDMMYYYY(s string) time.Time

ParseDateFromDDMMYYYY from string value

func ParseDateFromMMDD

func ParseDateFromMMDD(s string) time.Time

ParseDateFromMMDD from string value

func ParseDateFromMMYY

func ParseDateFromMMYY(s string) time.Time

ParseDateFromMMYY from string value

func ParseDateFromYYMM

func ParseDateFromYYMM(s string) time.Time

ParseDateFromYYMM from string value

func ParseDateFromYYMMDD

func ParseDateFromYYMMDD(s string) time.Time

ParseDateFromYYMMDD from string value

func ParseDateFromYYYYMMDD

func ParseDateFromYYYYMMDD(s string) time.Time

ParseDateFromYYYYMMDD from string value

func ParseDateTime

func ParseDateTime(s string) time.Time

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

func ParseDateTime24Hr(s string) time.Time

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

func ParseDateTimeCustom(s string, f string) time.Time

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

func ParseDateTimeFromMMDDYYYYhhmmss(s string) time.Time

ParseDateTimeFromMMDDYYYYhhmmss from string value

func ParseDateTimeFromYYYYMMDDhhmmss

func ParseDateTimeFromYYYYMMDDhhmmss(s string) time.Time

ParseDateTimeFromYYYYMMDDhhmmss from string value

func ParseDateTimeFrom_ISO8601_RFC3339 added in v1.3.4

func ParseDateTimeFrom_ISO8601_RFC3339(s string) time.Time

ParseDateTimeFrom_ISO8601_RFC3339 from string value of RFC3339 date time format

func ParseDateToLastDayOfMonth

func ParseDateToLastDayOfMonth(t time.Time) time.Time

ParseDateToLastDayOfMonth takes in a time.Time struct and returns the last date of month

func ParseEmvTlvTagNamesOnly added in v1.1.2

func ParseEmvTlvTagNamesOnly(emvTlvTagNamesPayload string) (foundList []string, err error)

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

func ParseFloat32(s string) (float32, bool)

ParseFloat32 tests and parses if input string is float 32 bit (decimal point value)

func ParseFloat64

func ParseFloat64(s string) (float64, bool)

ParseFloat64 tests and parses if input string is float 64 bit (decimal point value)

func ParseFromExcelDate added in v1.0.9

func ParseFromExcelDate(s string, format string) time.Time

ParseFromExcelDate will handle integer value of excel date to convert to time.Time

func ParseHostFromURL

func ParseHostFromURL(url string) string

ParseHostFromURL will parse out the host name from url

func ParseHttpHeader added in v1.1.4

func ParseHttpHeader(respHeader http.Header) (map[string]string, error)

ParseHttpHeader parses headers into map[string]string, where slice of header values for a key is delimited with semi-colon (;)

func ParseInt32

func ParseInt32(s string) (int, bool)

ParseInt32 tests and parses if input string is integer (whole numbers 32 bits)

func ParseInt64

func ParseInt64(s string) (int64, bool)

ParseInt64 tests and parses if input string is big integer (whole number greater 64 bits)

func ParseKeyValue

func ParseKeyValue(s string, delimiter string, key *string, val *string) error

ParseKeyValue will parse the input string using specified delimiter (= is default), result is set in the key and val fields

func ParseTime

func ParseTime(s string) time.Time

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

func ParseTimeFromhhmmss(s string) time.Time

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

func ReadHttpRequestBody(req *http.Request) ([]byte, error)

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

func ReadHttpRequestHeaders(req *http.Request) (map[string]string, error)

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

func ReflectGetType(obj interface{}) reflect.Type

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

func ReflectObjectNewPtr(objType reflect.Type) interface{}

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

func ReflectStringToField(o reflect.Value, v string, timeFormat string) error

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

func ReflectTypeRegistryAdd(customStructObj interface{}, customFullTypeName ...string) bool

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

func ReflectTypeRegistryGet(customFullTypeName string) reflect.Type

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 Replace

func Replace(s string, oldChar string, newChar string) string

Replace will replace old char with new char and return the replaced string

func Reverse

func Reverse(s string) string

Reverse a string

func Right(s string, l int) string

Right returns the right side of string indicated by variable l (size of substring)

func RightTrimLF

func RightTrimLF(s string) string

RightTrimLF will remove linefeed (return char) from the right most char and return result string

func RoundFloat64 added in v1.3.1

func RoundFloat64(val float64, precision uint) float64

RoundFloat64 converts float64 value to target precision

func RoundIntegerToNearestBlock added in v1.3.3

func RoundIntegerToNearestBlock(val int, blockSize int) int

RoundIntegerToNearestBlock returns conformed block size value where val fall into. For example: if val is 3 and blockSize is 5, then return value is 5; where as if val is 13 and blockSize is 5, then return value is 15; val must be > 0

func SecondsDiff

func SecondsDiff(timeFrom time.Time, timeTo time.Time) int

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

func SliceStringToCSVString(source []string, spaceAfterComma bool) string

SliceStringToCSVString unboxes slice of string into comma separated string

func SplitString

func SplitString(source string, delimiter string, index int) 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

func StrToInt64 added in v1.2.9

func StrToInt64(s string) int64

StrToInt64 converts from string to int64, if string is not a valid int64, 0 is returned.

func StrToUint

func StrToUint(s string) uint

StrToUint converts from string to uint, if string is not a valid uint, 0 is returned.

func StrToUint64 added in v1.1.1

func StrToUint64(s string) uint64

StrToUint64 converts from string to uint64, if string is not a valid uint64, 0 is returned.

func StringPtr

func StringPtr(s string) *string

StringPtr gets string pointer from string value.

func StringPtrToString

func StringPtrToString(s *string) string

StringPtrToString gets string value from string pointer, if pointer is nil, blank string is returned.

func StringSliceContains added in v1.0.9

func StringSliceContains(strSlice *[]string, value string) bool

StringSliceContains checks if value is contained within the strSlice

func StringSliceExtractUnique added in v1.1.5

func StringSliceExtractUnique(strSlice []string) (result []string)

StringSliceExtractUnique returns unique string slice elements

func StringToHex

func StringToHex(data string) string

StringToHex converts string into hex

func StringVal added in v1.1.1

func StringVal(s *string) string

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 TimePtr

func TimePtr(t time.Time) *time.Time

TimePtr casts Time struct to Time pointer.

func TimeVal added in v1.1.1

func TimeVal(t *time.Time) time.Time

TimeVal gets Time struct from Time pointer, if pointer is nil, a time.Time{} is returned.

func ToNullBool

func ToNullBool(b bool) sql.NullBool

ToNullBool sets bool into NullBool output

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 ToNullInt

func ToNullInt(d int, emptyAsNull bool) sql.NullInt32

ToNullInt sets int value into NullInt32 output

func ToNullInt64

func ToNullInt64(d int64, emptyAsNull bool) sql.NullInt64

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

func ToNullTime(t time.Time) sql.NullTime

ToNullTime sets time.Time into NullTime output

func Trim

func Trim(s string) string

Trim gets the left and right space trimmed input string s

func UInt64ToString

func UInt64ToString(n uint64) string

UInt64ToString converts uint64 value to string.

func UintPtr added in v1.1.1

func UintPtr(i uint) *uint

UintPtr gets uint pointer from uint value.

func UintToStr

func UintToStr(i uint) string

UintToStr converts from uint to string.

func UintVal added in v1.1.1

func UintVal(i *uint) uint

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:

  1. `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
  2. `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,
  3. `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
  4. `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
  5. `range:"x..y"` // data type range value when Type is N, if underlying data type is string, method will convert first before testing
  6. `req:"true"` // indicates data value is required or not, true or false
  7. `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)'
  8. `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
  9. `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
  10. `def:""` // default value to set into struct field in case unmarshal doesn't set the struct field value
  11. `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
  12. `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)
  13. `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)
  14. `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

func UnmarshalJSON(jsonData string, v interface{}) error

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:

  1. `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
  2. `def:""` // default value to set into struct field in case unmarshal doesn't set the struct field value
  3. `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
  4. `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)
  5. `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

func UnmarshalXML(xmlData string, v interface{}) error

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

func XMLFromEscaped(data string) string

XMLFromEscaped will un-escape the data whose &gt; &lt; &amp; &#37; &apos; &quot; are converted to > < & % ' "

func XMLToEscaped

func XMLToEscaped(data string) string

XMLToEscaped will escape the data whose xml special chars > < & % ' " are escaped into &gt; &lt; &amp; &#37; &apos; &quot;

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

func ParseEmvTlvTags(emvTlvTagsPayload string) (foundList []*EmvTlvTag, err error)

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

func ParseEncryptedTlvTags(encryptedTlvTagsPayload string) (foundList []*EmvTlvTag, err error)

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

type JsonTime time.Time

JsonTime provides custom Json marshal and unmarshal interface implementations. JsonTime marshals and unmarshal using RFC3339 time format

func ToJsonTime added in v1.1.6

func ToJsonTime(t time.Time) JsonTime

ToJsonTime converts time.Time to JsonTime

func ToJsonTimePtr added in v1.1.6

func ToJsonTimePtr(t time.Time) *JsonTime

ToJsonTimePtr converts time.Time to JsonTime pointer

func (*JsonTime) MarshalJSON added in v1.1.6

func (jt *JsonTime) MarshalJSON() ([]byte, error)

MarshalJSON marshals time value to format of RFC3339

func (*JsonTime) ToTime added in v1.1.6

func (jt *JsonTime) ToTime() time.Time

ToTime converts JsonTime to time.Time

func (*JsonTime) UnmarshalJSON added in v1.1.6

func (jt *JsonTime) UnmarshalJSON(b []byte) error

UnmarshalJSON unmarshal time value in format of RFC3339 to JsonTime

Jump to

Keyboard shortcuts

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