utils

package
v1.4.5-alpha1 Latest Latest
Warning

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

Go to latest
Published: Apr 30, 2019 License: MPL-2.0 Imports: 19 Imported by: 62

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

View Source
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

View Source
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]+)?`)
)
View Source
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

func CryptAsURLString(rawString string) string

CryptAsURLString encrypts given string with base64 and hex encoding

func CryptToURLString

func CryptToURLString(raw []byte) string

CryptToURLString encrypts given string with base64 and hex encoding

func DataTypeArrayBaseType

func DataTypeArrayBaseType(dataType string) string

DataTypeArrayBaseType returns data type of array elements

func DataTypeArrayOf

func DataTypeArrayOf(dataType string) string

DataTypeArrayOf adds array modifier to given dataType, returns "" for unknown types

func DataTypeIsArray

func DataTypeIsArray(dataType string) bool

DataTypeIsArray returns true if dataType is kind of array

func DataTypeIsFloat

func DataTypeIsFloat(dataType string) bool

DataTypeIsFloat returns true if dataType representation for GO language is float64 type

func DataTypeIsString

func DataTypeIsString(dataType string) bool

DataTypeIsString returns true if dataType representation for GO language is string type

func DataTypeWPrecision

func DataTypeWPrecision(dataType string, precision int) string

DataTypeWPrecision adds precision modifier to given dataType, returns "" for unknown types

func DataTypeWPrecisionAndScale

func DataTypeWPrecisionAndScale(dataType string, precision int, scale int) string

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

func DecodeJSONToStringKeyMap(jsonData interface{}) (map[string]interface{}, error)

DecodeJSONToStringKeyMap decodes json string to map[string]interface{} if it's possible

func DecryptData

func DecryptData(encodedData []byte) ([]byte, error)

DecryptData decrypts given data with crypto/cipher algorithm

func DecryptString

func DecryptString(data string) string

DecryptString decodes base64.StdEncoding string un-salting it and then decrypts it with crypto/cipher, returns original value or error

func DecryptURLString

func DecryptURLString(encodedString string) (string, error)

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

func EncryptData(data []byte) ([]byte, error)

EncryptData encrypts given data with crypto/cipher algorithm

func EncryptReader

func EncryptReader(rawReader io.Reader) (io.Reader, error)

EncryptReader decrypts given stream with crypto/cipher algorithm

func EncryptString

func EncryptString(data string) string

EncryptString encrypts string with crypto/cipher, salting it and makes base64.StdEncoding, returns blank string if encoding fails

func EncryptWriter

func EncryptWriter(rawWriter io.Writer) (io.Writer, error)

EncryptWriter encrypts given stream with crypto/cipher algorithm

func EscapeRegexSpecials

func EscapeRegexSpecials(value string) string

EscapeRegexSpecials returns regular expression special characters escaped value

func Explode

func Explode(value string, separators string) []string

Explode returns trimmed []string array of [separators] delimited values

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 GetKey

func GetKey() []byte

GetKey returns a key used in crypto/cipher algorithm

func GetPointer

func GetPointer(subject interface{}) (uintptr, error)

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

func InterfaceToTime(value interface{}) time.Time

InterfaceToTime converts interface{} to time.Time

func IsAmongStr

func IsAmongStr(option string, searchOptions ...string) bool

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

func IsInListStr(searchItem string, searchList []string) bool

IsInListStr searches for a string in []string slice

func IsMD5

func IsMD5(value string) bool

IsMD5 checks if value is MD5

func IsZeroTime

func IsZeroTime(value time.Time) bool

IsZeroTime checks time for zero value

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

func MakeTZTime(inTime time.Time, timeZone string) (time.Time, time.Duration)

MakeTZTime returns given time in specified timezone (current time.Locale() ignores) and offset from GMT in duration format

func MakeUTCOffsetTime

func MakeUTCOffsetTime(inTime time.Time, timeZone string) (time.Time, time.Duration)

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

func MakeUTCTime(inTime time.Time, timeZone string) (time.Time, time.Duration)

MakeUTCTime returns given time in UTC-00:00 timezone (current time.Locale() ignores) and offset from GMT in duration format

func MatchMapAValuesToMapB

func MatchMapAValuesToMapB(mapA map[string]interface{}, mapB map[string]interface{}) bool

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

func ParseTimeZone(timeZone string) (string, time.Duration)

ParseTimeZone returns zone name and it's offset from GMT

func PasswordCheck

func PasswordCheck(password string, input string) bool

PasswordCheck compare inputed password with stored one

func PasswordEncode

func PasswordEncode(password string, salt string) string

PasswordEncode encode inputed password with using salt, if no salt it will use default one

func RegisterTemplateFunction

func RegisterTemplateFunction(name string, function interface{}) error

RegisterTemplateFunction registers custom function within text template processing

func Round

func Round(value float64, round float64, precision int) float64

Round rounds value to given precision (roundOn=0.5 usual cases)

func RoundPrice

func RoundPrice(price float64) float64

RoundPrice normalize price after calculations, so it rounds it to money precision

func SetKey

func SetKey(key []byte) error

SetKey changes a key that package using for crypto/cipher algorithm

func SetTimeZoneName

func SetTimeZoneName(inTime time.Time, zoneName string) time.Time

SetTimeZoneName set name to zone for given time object

func SortByFunc

func SortByFunc(data interface{}, reverse bool, less func(a, b interface{}) bool) []interface{}

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

func SplitQuotedStringBy(text string, separators ...rune) []string

SplitQuotedStringBy splits string by character(s) unless it in quotes

func StrKeysInMap

func StrKeysInMap(mapObject interface{}, keys ...string) bool

StrKeysInMap checks presence of string keys in map

func StrToCamelCase

func StrToCamelCase(str string) string

Convert string from snake_case to camelCase format

func StrToSnakeCase

func StrToSnakeCase(str string) string

Convert string to snake_case format

func StringToFloat

func StringToFloat(value string) (float64, error)

StringToFloat converts string to float64

func StringToInteger

func StringToInteger(value string) (int, error)

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

func StringToType(value string, valueType string) (interface{}, error)

StringToType converts string coded value to type

func SyncGet

func SyncGet(subject interface{}, initBlank bool, path ...interface{}) (interface{}, error)

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 SyncLock

func SyncLock(subject interface{}) error

SyncLock holds mutex on a given subject

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

func TextTemplate(templateContents string, context map[string]interface{}) (string, error)

TextTemplate evaluates text template, returns error if not possible

func TimeToUTCTime

func TimeToUTCTime(inTime time.Time) time.Time

TimeToUTCTime returns a given time in UTC timezone (converts time.Locale() to offset for UTC time)

func ValidEmailAddress

func ValidEmailAddress(email string) bool

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

type DataType struct {
	Name      string
	Precision int
	Scale     int
	IsArray   bool
	IsKnown   bool
}

DataType represents data type details

func DataTypeParse

func DataTypeParse(typeName string) DataType

DataTypeParse tries to parse given string representation of datatype into DataType struct

func (*DataType) String

func (it *DataType) String() string

String makes a string value representation of current type

Jump to

Keyboard shortcuts

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