Documentation ¶
Overview ¶
Package utils provides a set of functions you should use to reduce and standardize repeatable cross packages code. So, it considered that application code will use utils package as often as can.
"datatypes.go" - contains set of data-type declaration and conversion routines
When you are writing an application code you should be aware of data-types application can work with.So, this file contains that information for you, in addition to set of types conversions routines. As utils package it is globally used byt all application parts it makes application to works a unified way on data-types. You should use this package routines to making types conversion to be sure other application parts will understand you. Example 1: ---------- x := map[string]interface{} {"a": 10, "b": "20", "c": true") y := utils.InterfaceToString(x) z := utils.InterfaceToMap(y) fmt.Println(x, z) xTime := utils.InterfaceToTime("2010-01-15 10:22") xFloat := utils.InterfaceToFloat64("2", 10) xBool := utils.InterfaceToBool("yes") fmt.Println(xTime, xFloat, xBool) Example 2: ---------- typeName := "[]string" typeValue := "1,2,3,4" typeInfo := utils.DataTypeParse( typeName ) if typeInfo.IsKnown && typeInfo.IsArray { typedValue := utils.InterfaceToArray( utils.StringToType(typeValue, typeName) ) for _, value := typedValue { fmt.Println(value) } }
"generic.go" - contains set of unclassified routines should be unified due to application.
Example: -------- x := map[string]interface{} {"a": "10", "b": "20") if utils.KeysInMapAndNotBlank(x, "a", "b") { fmt.Println( utils.InterfaceToInt(x[a]) + Utils.InterfaceToInt(x[b]) ) fmt.Println( utils.GetFirstMapValue(x) ) } y := utils.RoundPrice( utils.InterfaceToFloat("11.22241") ) fmt.Println(y) z := utils.SplitQuotedStringBy(`"a", "b"; "c,d", "e.f".`, ";,. ") fmt.Println(z) searchString := "just {sample} [code]" escapedSearchString := EscapeRegexSpecials(searchString) matched, err = regexp.MatchString(searchString, escapedSearchString) fmt.Println(matched, err)
"crypt.go" - provides an centralized way for bi-directional crypt of secure data.
Notes: - SetKey() makes change for entire application. So, if you want local effect you should restore it after usage - normally application should take care about SetKey() on init and you should not touch it - if SetKey() was not called during application init then default hard-coded key will be used Example 1: ---------- source := "just test" encoded := utils.EncryptStringBase64(source) decoded := utils.DecryptStringBase64(encoded) println( "'" + source + "' --encode--> '" + encoded + "' --decode--> '" + decoded + "'") Output: 'just test' --encode--> 'Ddryse1yNL5z' --decode--> 'just test' Example 2: ---------- sampleData := []byte("It is just a sample.") outFile, _ := os.OpenFile("sample.txt", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600) defer outFile.Close() writer, _ := utils.EncryptWriter(outFile) writer.Write(sampleData) inFile, _ := os.OpenFile("sample.txt", os.O_RDONLY, 0600) defer inFile.Close() reader, _ := utils.EncryptReader(inFile) readBuffer := make([]byte, 10) reader.Read(readBuffer) println(string(readBuffer)) reader.Read(readBuffer) println(string(readBuffer)) Output: It is just a sample.
"json.go" - contains set of json conversion related routines
Example: -------- x := map[string]interface{} {"a": "10", "b": "20"} y := utils.EncodeToJSONString(x) fmt.Println(y)
"templates.go" - endpoint to register new application scope template functions as well simplifies GO templates usage. In following sample "first" directive will be available to any code addressing text templates to utils.TextTemplate(...)
Example: -------- newFunc := func(identifier string, args ...interface{}) string { if len(args) > 0 { return utils.InterfaceToString(args[0]) } return "null" } utils.RegisterTemplateFunction("first", newFunc) context := map[string]interface{} {"a": 10, "label": "first argument: "} result, err := utils.TextTemplate(".label {{first .a}}", context)
Index ¶
- Constants
- Variables
- func CheckIsBlank(value interface{}) bool
- func Clone(subject interface{}) interface{}
- func CryptAsURLString(rawString string) string
- func CryptToURLString(raw []byte) string
- func DataTypeArrayBaseType(dataType string) string
- func DataTypeArrayOf(dataType string) string
- func DataTypeIsArray(dataType string) bool
- func DataTypeIsFloat(dataType string) bool
- func DataTypeIsString(dataType string) bool
- func DataTypeWPrecision(dataType string, precision int) string
- func DataTypeWPrecisionAndScale(dataType string, precision int, scale int) string
- func DecodeJSONToArray(jsonData interface{}) ([]interface{}, error)
- func DecodeJSONToInterface(jsonData interface{}) (interface{}, error)
- func DecodeJSONToStringKeyMap(jsonData interface{}) (map[string]interface{}, error)
- func DecryptData(encodedData []byte) ([]byte, error)
- func DecryptString(data string) string
- func DecryptURLString(encodedString string) (string, error)
- func EncodeToJSONString(inputData interface{}) string
- func EncryptData(data []byte) ([]byte, error)
- func EncryptReader(rawReader io.Reader) (io.Reader, error)
- func EncryptString(data string) string
- func EncryptWriter(rawWriter io.Writer) (io.Writer, error)
- func EscapeRegexSpecials(value string) string
- func Explode(value string, separators string) []string
- func GetFirstMapValue(mapObject interface{}, keys ...string) interface{}
- func GetKey() []byte
- func GetPointer(subject interface{}) (uintptr, error)
- func GetTemplateFunctions() map[string]interface{}
- func InterfaceToArray(value interface{}) []interface{}
- func InterfaceToBool(value interface{}) bool
- func InterfaceToFloat64(value interface{}) float64
- func InterfaceToInt(value interface{}) int
- func InterfaceToMap(value interface{}) map[string]interface{}
- func InterfaceToString(value interface{}) string
- func InterfaceToStringArray(value interface{}) []string
- func InterfaceToTime(value interface{}) time.Time
- func IsAmongStr(option string, searchOptions ...string) bool
- func IsInArray(searchValue interface{}, arrayObject interface{}) bool
- func IsInListStr(searchItem string, searchList []string) bool
- func IsMD5(value string) bool
- func IsZeroTime(value time.Time) bool
- func KeysInMapAndNotBlank(mapObject interface{}, keys ...interface{}) bool
- func MakeTZTime(inTime time.Time, timeZone string) (time.Time, time.Duration)
- func MakeUTCOffsetTime(inTime time.Time, timeZone string) (time.Time, time.Duration)
- func MakeUTCTime(inTime time.Time, timeZone string) (time.Time, time.Duration)
- func MatchMapAValuesToMapB(mapA map[string]interface{}, mapB map[string]interface{}) bool
- func ParseTimeZone(timeZone string) (string, time.Duration)
- func PasswordCheck(password string, input string) bool
- func PasswordEncode(password string, salt string) string
- func RegisterTemplateFunction(name string, function interface{}) error
- func Round(value float64, round float64, precision int) float64
- func RoundPrice(price float64) float64
- func SetKey(key []byte) error
- func SetTimeZoneName(inTime time.Time, zoneName string) time.Time
- func SortByFunc(data interface{}, reverse bool, less func(a, b interface{}) bool) []interface{}
- func SortMapByKeys(data []map[string]interface{}, reverse bool, keys ...string) []map[string]interface{}
- func SplitQuotedStringBy(text string, separators ...rune) []string
- func StrKeysInMap(mapObject interface{}, keys ...string) bool
- func StrToCamelCase(str string) string
- func StrToSnakeCase(str string) string
- func StringToFloat(value string) (float64, error)
- func StringToInteger(value string) (int, error)
- func StringToInterface(value string) interface{}
- func StringToType(value string, valueType string) (interface{}, error)
- func SyncGet(subject interface{}, initBlank bool, path ...interface{}) (interface{}, error)
- func SyncLock(subject interface{}) error
- func SyncMutex(subject interface{}) (*syncMutex, error)
- func SyncScalarLock(subject interface{}) error
- func SyncScalarUnlock(subject interface{}) error
- func SyncSet(subject interface{}, value interface{}, path ...interface{}) error
- func SyncUnlock(subject interface{}) error
- func TextTemplate(templateContents string, context map[string]interface{}) (string, error)
- func TimeToUTCTime(inTime time.Time) time.Time
- func ValidEmailAddress(email string) bool
- type DataType
Constants ¶
const ( ConstDataTypeID = "id" ConstDataTypeBoolean = "bool" ConstDataTypeVarchar = "varchar" ConstDataTypeText = "text" ConstDataTypeInteger = "int" ConstDataTypeDecimal = "decimal" ConstDataTypeMoney = "money" ConstDataTypeFloat = "float" ConstDataTypeDatetime = "datetime" ConstDataTypeJSON = "json" ConstDataTypeHTML = "html" )
set of known data types
Variables ¶
var ( // StaticTypeRegexp is a regular expression used to parse datatype StaticTypeRegexp = regexp.MustCompile(`^\s*(\[\])?(\w+)\s*(?:\(\s*(\d+)?\s*(?:\)|,\s*(\d+)\s*\)))?$`) // StaticTimezoneRegexp is a regular expression used to parse time zone StaticTimezoneRegexp = regexp.MustCompile(`((?: [A-Za-z]+[ ]?[+-]?|Z| [+-])(?:[0-9]{1,2}(?::?[0-9]{1,2})?)?)([ ]*[A-Za-z]+)?`) )
var TimeZones = map[string]time.Duration{}/* 214 elements not displayed */
TimeZones list of known Time Zone Abbreviations – Worldwide List
Functions ¶
func CheckIsBlank ¶
func CheckIsBlank(value interface{}) bool
CheckIsBlank checks if value is blank (zero value)
func Clone ¶
func Clone(subject interface{}) interface{}
Clone will create a replica for a given object
func CryptAsURLString ¶
CryptAsURLString encrypts given string with base64 and hex encoding
func CryptToURLString ¶
CryptToURLString encrypts given string with base64 and hex encoding
func DataTypeArrayBaseType ¶
DataTypeArrayBaseType returns data type of array elements
func DataTypeArrayOf ¶
DataTypeArrayOf adds array modifier to given dataType, returns "" for unknown types
func DataTypeIsArray ¶
DataTypeIsArray returns true if dataType is kind of array
func DataTypeIsFloat ¶
DataTypeIsFloat returns true if dataType representation for GO language is float64 type
func DataTypeIsString ¶
DataTypeIsString returns true if dataType representation for GO language is string type
func DataTypeWPrecision ¶
DataTypeWPrecision adds precision modifier to given dataType, returns "" for unknown types
func DataTypeWPrecisionAndScale ¶
DataTypeWPrecisionAndScale adds precision and scale modifier to given dataType, returns "" for unknown types
func DecodeJSONToArray ¶
func DecodeJSONToArray(jsonData interface{}) ([]interface{}, error)
DecodeJSONToArray decodes json string to []interface{} if it's possible
func DecodeJSONToInterface ¶
func DecodeJSONToInterface(jsonData interface{}) (interface{}, error)
DecodeJSONToInterface decodes json string to interface{} if it's possible
func DecodeJSONToStringKeyMap ¶
DecodeJSONToStringKeyMap decodes json string to map[string]interface{} if it's possible
func DecryptData ¶
DecryptData decrypts given data with crypto/cipher algorithm
func DecryptString ¶
DecryptString decodes base64.StdEncoding string un-salting it and then decrypts it with crypto/cipher, returns original value or error
func DecryptURLString ¶
DecryptURLString decode given encoded string and returns decoded value
func EncodeToJSONString ¶
func EncodeToJSONString(inputData interface{}) string
EncodeToJSONString encodes inputData to JSON string if it's possible
func EncryptData ¶
EncryptData encrypts given data with crypto/cipher algorithm
func EncryptReader ¶
EncryptReader decrypts given stream with crypto/cipher algorithm
func EncryptString ¶
EncryptString encrypts string with crypto/cipher, salting it and makes base64.StdEncoding, returns blank string if encoding fails
func EncryptWriter ¶
EncryptWriter encrypts given stream with crypto/cipher algorithm
func EscapeRegexSpecials ¶
EscapeRegexSpecials returns regular expression special characters escaped value
func GetFirstMapValue ¶
func GetFirstMapValue(mapObject interface{}, keys ...string) interface{}
GetFirstMapValue returns map key value or nil if not found, will be returned first found key value
func GetPointer ¶
GetPointer returns the memory address value for a given subject or an error for scalar values
func GetTemplateFunctions ¶
func GetTemplateFunctions() map[string]interface{}
GetTemplateFunctions returns clone of templateFuncs (safe to manipulate)
func InterfaceToArray ¶
func InterfaceToArray(value interface{}) []interface{}
InterfaceToArray converts interface{} to []interface{}
func InterfaceToBool ¶
func InterfaceToBool(value interface{}) bool
InterfaceToBool converts interface{} to string
func InterfaceToFloat64 ¶
func InterfaceToFloat64(value interface{}) float64
InterfaceToFloat64 converts interface{} to float64
func InterfaceToInt ¶
func InterfaceToInt(value interface{}) int
InterfaceToInt converts interface{} to integer
func InterfaceToMap ¶
func InterfaceToMap(value interface{}) map[string]interface{}
InterfaceToMap converts interface{} to map[string]interface{}
func InterfaceToString ¶
func InterfaceToString(value interface{}) string
InterfaceToString converts interface{} to string
func InterfaceToStringArray ¶
func InterfaceToStringArray(value interface{}) []string
InterfaceToStringArray converts interface{} to []string
func InterfaceToTime ¶
InterfaceToTime converts interface{} to time.Time
func IsAmongStr ¶
IsAmongStr searches for presence of 1-st arg string option among provided options since 2-nd argument
func IsInArray ¶
func IsInArray(searchValue interface{}, arrayObject interface{}) bool
IsInArray searches for item in array/slice, returns true if found
func IsInListStr ¶
IsInListStr searches for a string in []string slice
func KeysInMapAndNotBlank ¶
func KeysInMapAndNotBlank(mapObject interface{}, keys ...interface{}) bool
KeysInMapAndNotBlank checks presence of non blank values for keys in map
- first arg must be map
- fallowing arguments are map keys you want to check
func MakeTZTime ¶
MakeTZTime returns given time in specified timezone (current time.Locale() ignores) and offset from GMT in duration format
func MakeUTCOffsetTime ¶
MakeUTCOffsetTime returns given time in UTC offset timezone (i.e. PST = UTC-08:00, current time.Locale() ignores) and offset from GMT in duration format
func MakeUTCTime ¶
MakeUTCTime returns given time in UTC-00:00 timezone (current time.Locale() ignores) and offset from GMT in duration format
func MatchMapAValuesToMapB ¶
MatchMapAValuesToMapB compares key values of mapA to same key value of mapB, returns true if all keys in mapA present and matches keys in mapB
func ParseTimeZone ¶
ParseTimeZone returns zone name and it's offset from GMT
func PasswordCheck ¶
PasswordCheck compare inputed password with stored one
func PasswordEncode ¶
PasswordEncode encode inputed password with using salt, if no salt it will use default one
func RegisterTemplateFunction ¶
RegisterTemplateFunction registers custom function within text template processing
func RoundPrice ¶
RoundPrice normalize price after calculations, so it rounds it to money precision
func SetTimeZoneName ¶
SetTimeZoneName set name to zone for given time object
func SortByFunc ¶
SortByFunc sorts slice with a given comparator function
- to sort in ascending order pass reverse as false
- to sort in descending order pass reverse as true
func SortMapByKeys ¶
func SortMapByKeys(data []map[string]interface{}, reverse bool, keys ...string) []map[string]interface{}
SortMapByKeys sorts given map by specified keys values
- to sort in ascending order pass reverse as false
- to sort in descending order pass reverse as true
func SplitQuotedStringBy ¶
SplitQuotedStringBy splits string by character(s) unless it in quotes
func StrKeysInMap ¶
StrKeysInMap checks presence of string keys in map
func StrToCamelCase ¶
Convert string from snake_case to camelCase format
func StringToFloat ¶
StringToFloat converts string to float64
func StringToInteger ¶
StringToInteger converts string to integer
func StringToInterface ¶
func StringToInterface(value string) interface{}
StringToInterface converts string to Interface{} which can be float, int, bool, string, or json as map[string]value
func StringToType ¶
StringToType converts string coded value to type
func SyncGet ¶
SyncGet - synchronized read access tree like variables
- the -1 index for a slice means to init new blank slice value
sample:
var x map[string]map[int][]int = ... // un-synchronized access to value - causes simultaneous read/write access panics for parallel threade y := x["a"][5][1] // synchronized access to variable y := SyncGet(x, false, "a", 5, 1) // returns x["a"][5][1], or (nil, error) if item does not exist y := SyncGet(x, true, "a", 5, -1) // returns new blank value of list for a possibly new element x["a"][5]
func SyncMutex ¶
func SyncMutex(subject interface{}) (*syncMutex, error)
SyncMutex creates a mutex element for a given subject or error for a scalar values (un-addressable values)
func SyncScalarLock ¶
func SyncScalarLock(subject interface{}) error
ScalarSyncLock holds mutex on a given scalar subject.
func SyncScalarUnlock ¶
func SyncScalarUnlock(subject interface{}) error
ScalarSyncUnlock releases mutex on a given scalar subject. It forgets subject if no more refs exists.
func SyncSet ¶
func SyncSet(subject interface{}, value interface{}, path ...interface{}) error
SyncSet - synchronized write access to tree like variables
- the value could be a func(oldValue {type}) {type} which would be synchronized called
- the -1 index for a slice means it's extensions for a new element
func SyncUnlock ¶
func SyncUnlock(subject interface{}) error
SyncUnlock releases mutex on a given subject
func TextTemplate ¶
TextTemplate evaluates text template, returns error if not possible
func TimeToUTCTime ¶
TimeToUTCTime returns a given time in UTC timezone (converts time.Locale() to offset for UTC time)
func ValidEmailAddress ¶
ValidEmailAddress takes an email address as string compares it agasint a regular expression - returns true if email address is in a valid format - returns false if email address is not in a valid format
Types ¶
type DataType ¶
DataType represents data type details
func DataTypeParse ¶
DataTypeParse tries to parse given string representation of datatype into DataType struct