README

GitHub GitHub Go Report Card Coverage Status Build Status Mentioned in Awesome Go CircleCI

Handy Go utilities

GO Golang Utilities and helpers like validators, sanitizers and string formatters

Dependencies

None, since v1.1.1


Documentation 📗
GoDocs


Quality 👈
GoCover

Functions

// CheckEmail returns true if the given sequence is a valid email address
// See https://tools.ietf.org/html/rfc2822#section-3.4.1 for details about email address anatomy
func CheckEmail(email string) bool {}

// CheckNewPassword Run some basic checks on new password strings, based on given options
// This routine requires at least 4 (four) characters
// Example requiring only basic minimum lenght: CheckNewPassword("lalala", "lalala", 10, CheckNewPasswordComplexityLowest)
// Example requiring number and symbol: CheckNewPassword("lalala", "lalala", 10, CheckNewPasswordComplexityRequireNumber|CheckNewPasswordComplexityRequireSymbol)
func CheckNewPassword(password, passwordConfirmation string, minimumLenght uint, flagComplexity uint8) uint8 {

// StringHash simply generates a SHA256 hash from the given string
func StringHash(s string) string {}

// OnlyLetters returns only the letters from the given string, after strip all the rest ( numbers, spaces, etc. )
func OnlyLetters(sequence string) string {}

// OnlyDigits returns only the numbers from the given string, after strip all the rest ( letters, spaces, etc. )
func OnlyDigits(sequence string) string {}

// OnlyLettersAndNumbers returns only the letters and numbers from the given string, after strip all the rest, like spaces and special symbols.
func OnlyLettersAndNumbers(sequence string) string {}

// RandomInt returns a rondom integer within the given (inclusive) range
func RandomInt(min, max int) int {}

// StringAsFloat tries to convert a string to float, and if it can't, just returns zero
// It's limited to one billion
func StringAsFloat(s string, decimalSeparator, thousandsSeparator rune) float64 {}

// StringAsInteger returns the integer value extracted from string, or zero
func StringAsInteger(s string) int {}

// Between checks if param n in between low and high integer params
func Between(n, low, high int) bool {}

// Tif is a simple implementation of the dear ternary IF operator
func Tif(condition bool, tifThen, tifElse interface{}) interface{} {}

// Truncate limits the length of a given string, trimming or not, according parameters
func Truncate(s string, maxLen int, trim bool) string {}

// Transform handles a string according given flags/parametrization, as follows:
// Available Flags to be used alone or combined:
//	TransformNone - Does nothing. It's only for truncation.
//	TransformFlagTrim - Trim spaces before and after proccess the input
//	TransformFlagLowerCase - Change string case to lower
//	TransformFlagUpperCase - Change string case to upper
//	TransformFlagOnlyDigits - Filter/strip all but digits
//	TransformFlagOnlyLetters - Filter/strip all but letters
//	TransformFlagOnlyLettersAndDigits - Filter/strip all but numbers and letters. Removes spaces, punctuation and special symbols
// 	TransformFlagHash - Apply handy.StringHash() routine to string
func Transform(s string, maxLen int, transformFlags uint8) string {}

// MatchesAny returns true if any of the given items matches ( equals ) the subject ( search parameter )
func MatchesAny(search interface{}, items ...interface{}) bool {}

// HasOnlyNumbers returns true if the sequence is entirely numeric
func HasOnlyNumbers(sequence string) bool {}

// HasOnlyNumbers returns true if the sequence is entirely composed by letters
func HasOnlyLetters(sequence string) bool {}

// TrimLen returns the runes count after trim the spaces
func TrimLen(text string) int {}

// CheckMinLen verifies if the rune-count is greater then or equal the given minimum
// It returns true if the given string has length greater than or equal than minLength parameter
func CheckMinLen(value string, minLength int) bool {}

// IsNumericType checks if an interface's concrete type corresponds to some of golang native numeric types
func IsNumericType(x interface{}) bool {}

// Bit returns only uint8(0) or uint8(1).
// It receives an interface, and when it's a number, and when this number is 0 (zero) it returns 0. Otherwise it returns 1 (one)
// If the interface is not a number, it returns 0 (zero)
func Bit(x interface{}) uint8 {}

// Boolean returns the bool version/interpretation of some value;
// It receives an interface, and when this is a number, Boolean() returns flase of zero and true for different from zero.
// If it's a string, try to find "1", "T", "TRUE" to return true.
// Any other case returns false
func Boolean(x interface{}) bool {}

// Reverse returns the given string written backwards, with letters reversed.
func Reverse(s string) string {}

// CheckPersonName returns true if the name contains at least two words, one >= 3 chars and one >=2 chars.
// I understand that this is a particular criteria, but this is the OpenSourceMagic, where you can change and adapt to your own specs.
func CheckPersonName(name string, acceptEmpty bool) uint8 {}

// InArray searches for "item" in "array" and returns true if it's found
// This func resides here alone only because its long size.
// TODO Embrace/comprise all native scalar/primitive types
func InArray(array interface{}, item interface{}) bool {}

// ArrayDifferenceAtoB returns the items from A that doesn't exist in B
func ArrayDifferenceAtoB(a, b []int) []int {}

// ArrayDifference returns all items that doesn't exist in both given arrays
func ArrayDifference(a, b []int) []int {}


/* DateTime Routines */

// DateTimeAsString formats time.Time variables as strings, considering the format directive
func DateTimeAsString(dt time.Time, format string) string {}

// StringAsDateTime converts a date-time string using given format string and return it as time.Time
func StringAsDateTime(s string, format string) time.Time {}

// CheckDate validates a date using the given format
func CheckDate(format, dateTime string) bool {

// CheckDate returns true if given sequence is a valid date in format yyyymmdd
// The function removes non-digit characteres like "yyyy/mm/dd" or "yyyy-mm-dd", filtering to "yyyymmdd"
func CheckDateYMD(yyyymmdd string) bool {}

// YMDasDateUTC returns a valid UTC time from the given yyymmdd-formatted sequence
func YMDasDateUTC(yyyymmdd string, utc bool) (time.Time, error) {}

// YMDasDate returns a valid time from the given yyymmdd-formatted sequence
func YMDasDate(yyyymmdd string) (time.Time, error) {}

// ElapsedMonths returns the number of elapsed months between two given dates
func ElapsedMonths(from, to time.Time) int {}

// ElapsedYears returns the number of elapsed years between two given dates
func ElapsedYears(from, to time.Time) int {}

// YearsAge returns the number of years past since a given date
func YearsAge(birthdate time.Time) int {}

/* Brazilian specific routines */

// CheckCPF returns true if the given sequence is a valid cpf
// CPF is the Brazilian TAXPayerID document for persons
func CheckCPF(cpf string) bool {}

// CheckCNPJ returns true if the cnpj is valid
// Thanks to https://gopher.net.br/validacao-de-cpf-e-cnpj-em-go/
// CNPJ is the Brazilian TAXPayerID document for companies
func CheckCNPJ(cnpj string) bool {}

// AmountAsWord receives an int64 e returns the value as its text representation
// Today I have only the PT-BR text.
// Ex: AmountAsWord(129) => "cento e vinte e nove"
// Supports up to one trillion and does not add commas.
func AmountAsWord(n int64) string {}

/* Web/HTTP Specific Routines */

// HTTPRequestAsString gets a parameter coming from a http request as string, truncated to maxLenght
// Only maxLenght >= 1 is considered. Otherwise, it's ignored
func HTTPRequestAsString(r *http.Request, key string, maxLenght int, transformOptions ...uint8) string {}

// HTTPRequestAsInteger gets a parameter coming from a http request as an integer
// It tries to guess if it's a signed/negative integer
func HTTPRequestAsInteger(r *http.Request, key string) int {}

// HTTPRequestAsFloat64 gets a parameter coming from a http request as float64 number
// You have to inform the decimal separator symbol.
// If decimalSeparator is period, engine considers thousandSeparator is comma, and vice-versa.
func HTTPRequestAsFloat64(r *http.Request, key string, decimalSeparator rune) float64 {}

/* Other Routines  */

// CheckPersonNameResult returns a meaningful message describing the code generated bu CheckPersonName
// The routine considers the given idiom. The fallback is in english
func CheckPersonNameResult(idiom string, r uint8) string {}

// CheckNewPasswordResult returns a meaningful message describing the code generated bu CheckNewPassword()
// The routine considers the given idiom. The fallback is in english
func CheckNewPasswordResult(idiom string, r uint8) string {}


Documentation

Overview

Package handy is a toolbelt with utilities and helpers like validators, sanitizers and string formatters. There are routines to filter strings, convert between types, validate passwords with custom rules, easily format dates and much more.

Index

Constants

View Source
const (

	// CheckNewPasswordResultOK Means the checking ran alright
	CheckNewPasswordResultOK = 0
	// CheckNewPasswordResultDivergent Password is different from confirmation
	CheckNewPasswordResultDivergent = 1
	// CheckNewPasswordResultTooShort Password is too short
	CheckNewPasswordResultTooShort = 2
	// CheckNewPasswordResultTooSimple Given string doesn't satisfy complexity rules
	CheckNewPasswordResultTooSimple = 3

	// CheckNewPasswordComplexityLowest There's no rules besides the minimum length
	// >>> This flag turns all others off <<<
	CheckNewPasswordComplexityLowest = 1
	// CheckNewPasswordComplexityRequireLetter At least one letter is required in order to aprove password
	CheckNewPasswordComplexityRequireLetter = 2
	// CheckNewPasswordComplexityRequireUpperCase At least one uppercase letter is required in order to aprove password.
	// Only works if CheckNewPasswordComplexityRequireLetter is included/activated
	CheckNewPasswordComplexityRequireUpperCase = 4
	// CheckNewPasswordComplexityRequireNumber At least one number is required in order to aprove password
	CheckNewPasswordComplexityRequireNumber = 8
	// CheckNewPasswordComplexityRequireSpace The password must contain at least one space
	CheckNewPasswordComplexityRequireSpace = 16
	// CheckNewPasswordComplexityRequireSymbol User have to include at least one special character, like # or -
	CheckNewPasswordComplexityRequireSymbol = 32
)
View Source
const (
	// TransformNone No transformations are ordered. Only constraints maximum length
	// TransformNone turns all other flags OFF.
	TransformNone = 1
	// TransformFlagTrim Trim spaces before and after process the input
	// TransformFlagTrim Trims the string, removing leading and trailing spaces
	TransformFlagTrim = 2
	// TransformFlagLowerCase Makes the string lowercase
	// If case transformation flags are combined, the last one remains, considering the following order: TransformFlagTitleCase, TransformFlagLowerCase and TransformFlagUpperCase.
	TransformFlagLowerCase = 4
	// TransformFlagUpperCase Makes the string uppercase
	// If case transformation flags are combined, the last one remains, considering the following order: TransformFlagTitleCase, TransformFlagLowerCase and TransformFlagUpperCase.
	TransformFlagUpperCase = 8
	// TransformFlagOnlyDigits Removes all non-numeric characters
	TransformFlagOnlyDigits = 16
	// TransformFlagOnlyLetters Removes all non-letter characters
	TransformFlagOnlyLetters = 32
	// TransformFlagOnlyLettersAndDigits Leaves only letters and numbers
	TransformFlagOnlyLettersAndDigits = 64
	// TransformFlagHash After process all other flags, applies SHA256 hashing on string for output
	// 	The routine applies handy.StringHash() on given string
	TransformFlagHash = 128
	// TransformFlagTitleCase Makes the string uppercase
	// If case transformation flags are combined, the last one remains, considering the following order: TransformFlagTitleCase, TransformFlagLowerCase and TransformFlagUpperCase.
	TransformFlagTitleCase = 256
	// TransformFlagRemoveDigits Removes all digit characters, without to touch on any other
	// If combined with TransformFlagOnlyLettersAndDigits, TransformFlagOnlyDigits or TransformFlagOnlyLetters, it's ineffective
	TransformFlagRemoveDigits = 512
)
View Source
const (
	// CheckStrAllowEmpty allows empty string ""
	CheckStrAllowEmpty = 1
	// CheckStrDenySpaces forbids spaces, tabs, new lines and carriage return
	CheckStrDenySpaces = 2
	// CheckStrDenyNumbers forbids digits/numbers
	CheckStrDenyNumbers = 4
	// CheckStrDenyLetters forbids letters
	CheckStrDenyLetters = 8
	// CheckStrDenySymbols forbids symbols. if it's not a number, letter or space, is considered a symbol
	CheckStrDenySymbols = 16
	// CheckStrDenyMoreThanOneWord forbids more than one word
	CheckStrDenyMoreThanOneWord = 32
	// CheckStrDenyUpperCase forbids uppercase letters
	CheckStrDenyUpperCase = 64
	// CheckStrDenyLowercase forbids lowercase letters
	CheckStrDenyLowercase = 128
	// CheckStrDenyUnicode forbids non-ASCII characters
	CheckStrDenyUnicode = 256
	// CheckStrRequireNumbers demands at least 1 number within string
	CheckStrRequireNumbers = 512
	// CheckStrRequireLetters demands at least 1 letter within string
	CheckStrRequireLetters = 1024
	// CheckStrRequireSymbols demands at least 1 symbol within string. if it's not a number, letter or space, is considered a symbol
	CheckStrRequireSymbols = 2048
	// CheckStrRequireMoreThanOneWord demands at least 2 words in given string input
	CheckStrRequireMoreThanOneWord = 4096
	// CheckStrRequireUpperCase demands at least 1 uppercase letter within string
	CheckStrRequireUpperCase = 8192
	// CheckStrRequireLowercase demands at least 1 lowercase letter within string
	CheckStrRequireLowercase = 16384

	// CheckStrOk means "alright"
	CheckStrOk = 0
	// CheckStrEmptyDenied is self explained
	CheckStrEmptyDenied = -1
	// CheckStrTooShort is self explained
	CheckStrTooShort = -2
	// CheckStrTooLong is self explained
	CheckStrTooLong = -4
	// CheckStrSpaceDenied is self explained
	CheckStrSpaceDenied = -5
	// CheckStrNubersDenied is self explained
	CheckStrNubersDenied = -6
	// CheckStrLettersDenied is self explained
	CheckStrLettersDenied = -7
	// CheckStrSymbolsDenied is self explained
	CheckStrSymbolsDenied = -8
	// CheckStrMoreThanOneWordDenied is self explained
	CheckStrMoreThanOneWordDenied = -9
	// CheckStrUpperCaseDenied is self explained
	CheckStrUpperCaseDenied = -10
	// CheckStrLowercaseDenied is self explained
	CheckStrLowercaseDenied = -11
	// CheckStrUnicodeDenied is self explained
	CheckStrUnicodeDenied = -12

	// CheckStrNumbersNotFound is self explained
	CheckStrNumbersNotFound = -13
	// CheckStrLettersNotFound is self explained
	CheckStrLettersNotFound = -14
	// CheckStrSymbolsNotFound is self explained
	CheckStrSymbolsNotFound = -15
	// CheckStrMoreThanOneWordNotFound is self explained
	CheckStrMoreThanOneWordNotFound = -16
	// CheckStrUpperCaseNotFound is self explained
	CheckStrUpperCaseNotFound = -17
	// CheckStrLowercaseNotFound is self explained
	CheckStrLowercaseNotFound = -18
)
View Source
const (
	// CheckPersonNameResultOK means the name was validated
	CheckPersonNameResultOK = 0
	// CheckPersonNameResultPolluted The routine only accepts letters, single quotes and spaces
	CheckPersonNameResultPolluted = 1
	// CheckPersonNameResultTooFewWords The funcion requires at least 2 words
	CheckPersonNameResultTooFewWords = 2
	// CheckPersonNameResultTooShort the sum of all characters must be >= 6
	CheckPersonNameResultTooShort = 3
	// CheckPersonNameResultTooSimple The name rule requires that at least one word
	CheckPersonNameResultTooSimple = 4
)

Variables

This section is empty.

Functions

func AmountAsWord

func AmountAsWord(n int64) string

AmountAsWord receives an int64 e returns the value as its text representation Today I have only the PT-BR text. Ex: AmountAsWord(129) => "cento e vinte e nove" Supports up to one trillion and does not add commas.

func ArrayDifference

func ArrayDifference(a, b []int) []int

ArrayDifference returns all items that doesn't exist in both given arrays

func ArrayDifferenceAtoB

func ArrayDifferenceAtoB(a, b []int) []int

ArrayDifferenceAtoB returns the items from A that doesn't exist in B

func Between

func Between(n, low, high int) bool

Between checks if param n in between low and high integer params

func Bit

func Bit(x interface{}) uint8

Bit returns only uint8(0) or uint8(1). It receives an interface, and when it's a number, and when this number is 0 (zero) it returns 0. Otherwise it returns 1 (one) If the interface is not a number, it returns 0 (zero)

func Boolean

func Boolean(x interface{}) bool

Boolean returns the bool version/interpretation of some value; It receives an interface, and when this is a number, Boolean() returns flase of zero and true for different from zero. If it's a string, try to find "1", "T", "TRUE" to return true. Any other case returns false

func CheckCNPJ

func CheckCNPJ(cnpj string) bool

CheckCNPJ returns true if the cnpj is valid Thanks to https://gopher.net.br/validacao-de-cpf-e-cnpj-em-go/ CNPJ is the Brazilian TAXPayerID document for companies

func CheckCPF

func CheckCPF(cpf string) bool

CheckCPF returns true if the given input is a valid cpf CPF is the Brazilian TAXPayerID document for persons

func CheckDate

func CheckDate(format, dateTime string) bool

CheckDate validates a date using the given format

func CheckDateYMD

func CheckDateYMD(yyyymmdd string) bool

CheckDateYMD returns true if given input is a valid date in format yyyymmdd The function removes non-digit characters like "yyyy/mm/dd" or "yyyy-mm-dd", filtering to "yyyymmdd"

func CheckEmail

func CheckEmail(email string) bool

CheckEmail returns true if the given input is a valid email address Observe that CheckEmail doesn't trim nor sanitize string before check See https://tools.ietf.org/html/rfc2822#section-3.4.1 for details about email address anatomy

func CheckMinLen

func CheckMinLen(value string, minLength int) bool

CheckMinLen verifies if the rune-count is greater then or equal the given minimum It returns true if the given string has length greater than or equal than minLength parameter

func CheckNewPassword

func CheckNewPassword(password, passwordConfirmation string, minimumlength uint, flagComplexity uint8) uint8

CheckNewPassword Run some basic checks on new password strings, based on given options This routine requires at least 4 (four) characters Example requiring only basic minimum length: CheckNewPassword("lalala", "lalala", 10, CheckNewPasswordComplexityLowest) Example requiring number and symbol: CheckNewPassword("lalala", "lalala", 10, CheckNewPasswordComplexityRequireNumber|CheckNewPasswordComplexityRequireSymbol)

func CheckNewPasswordResult

func CheckNewPasswordResult(idiom string, r uint8) string

CheckNewPasswordResult returns a meaningful message describing the code generated bu CheckNewPassword() The routine considers the given idiom. The fallback is in english

func CheckPersonName

func CheckPersonName(name string, acceptEmpty bool) uint8

CheckPersonName returns true if the name contains at least two words, one >= 3 chars and one >=2 chars. I understand that this is a particular criteria, but this is the OpenSourceMagic, where you can change and adapt to your own specs.

func CheckPersonNameResult

func CheckPersonNameResult(idiom string, r uint8) string

CheckPersonNameResult returns a meaningful message describing the code generated bu CheckPersonName The routine considers the given idiom. The fallback is in english

func CheckPhone

func CheckPhone(phone string, acceptEmpty bool) bool

CheckPhone returns true if a given input has between 9 and 14 digits

func CheckStr

func CheckStr(seq string, minLen, maxLen uint, rules uint64) int8

CheckStr validates a string according given complexity rules CheckStr first evaluates "Deny" rules, and then "Require" rules. minLen=0 means there's no minimum length maxLen=0 means there's no maximum length

func CleanSpaces

func CleanSpaces(s string) string

CleanSpaces removes duplicated spaces, tabs and newLine characters and then trim string's both sides

func DateReformat

func DateReformat(dt1 string, currentFormat, newFormat string) string

DateReformat gets a date string in a given currentFormat, and transform it according newFormat

func DateStrCheckErrMessage

func DateStrCheckErrMessage(idiom string, errCode DateStrCheck) string

func DateTimeAsString

func DateTimeAsString(dt time.Time, format string) string

DateTimeAsString formats time.Time variables as strings, considering the format directive

func DedupSpaces

func DedupSpaces(s string) string

DedupSpaces removes duplicated spaces, tabs and newLine characters I.E: Replaces two tabs for one single tab

func ElapsedMonths

func ElapsedMonths(from, to time.Time) int

ElapsedMonths returns the number of elapsed months between two given dates

func ElapsedTime

func ElapsedTime(dtx, dty time.Time) (int, int, int, int, int, int)

ElapsedTime returns difference between two dates in years, months, days, hours, monutes and seconds Thanks to icza@https://stackoverflow.com/a/36531443/1301019

func ElapsedYears

func ElapsedYears(from, to time.Time) int

ElapsedYears returns the number of elapsed years between two given dates

func HTTPAnswerJSON

func HTTPAnswerJSON(w http.ResponseWriter, data interface{}) error

HTTPAnswerJSON converts the given data as json, set the content-type header and write it to requester

func HTTPJSONBodyToStruct

func HTTPJSONBodyToStruct(r *http.Request, targetStruct interface{}) bool

HTTPJSONBodyToStruct decode json to a given anatomically compatible struct THIS ROUTINE IS BEEN DEPRECATED. Use HTTPJSONToStruct() instead.

func HTTPJSONToStruct

func HTTPJSONToStruct(r *http.Request, targetStruct interface{}, closeBody bool) error

HTTPJSONToStruct decode json to a given anatomically compatible struct the differences to HTTPJSONBodyToStruct is that: - HTTPJSONToStruct can condittionally close body after unmarshalling - HTTPJSONToStruct returns an error instead of a bool

func HTTPRequestAsFloat64

func HTTPRequestAsFloat64(r *http.Request, key string, decimalSeparator rune) float64

HTTPRequestAsFloat64 gets a parameter coming from a http request as float64 number You have to inform the decimal separator symbol. If decimalSeparator is period, engine considers thousandSeparator is comma, and vice-versa.

func HTTPRequestAsInteger

func HTTPRequestAsInteger(r *http.Request, key string) int

HTTPRequestAsInteger gets a parameter coming from a http request as an integer It tries to guess if it's a signed/negative integer

func HTTPRequestAsString

func HTTPRequestAsString(r *http.Request, key string, maxLength int, transformOptions ...uint) string

HTTPRequestAsString gets a parameter coming from a http request as string, truncated to maxLength Only maxLength >= 1 is considered. Otherwise, it's ignored

func HasLetter

func HasLetter(s string) bool

HasLetter returns true if input string contains at least one letter

func HasNumber

func HasNumber(s string) bool

HasNumber returns true if input string contains at least one digit/number

func HasOnlyLetters

func HasOnlyLetters(sequence string) bool

HasOnlyLetters returns true if the input is entirely composed by letters

func HasOnlyNumbers

func HasOnlyNumbers(sequence string) bool

HasOnlyNumbers returns true if the input is entirely numeric

func HasSymbol

func HasSymbol(s string) bool

HasSymbol returns true if input string contains at least one symbol If rune is not a space, letter nor a number, it's considered a symbol

func InArray

func InArray(array interface{}, item interface{}) bool

InArray searches for "item" in "array" and returns true if it's found This func resides here alone only because its long size. TODO Embrace/comprise all native scalar/primitive types

func InArrayIntFlex

func InArrayIntFlex(item interface{}, array interface{}) bool

InArrayIntFlex returns true if "item" exists in "array" item and array can be of different kinds, since they're integer types array param should be an array of any integer type (int,int8,int16,int32,int64,uint,uint8,uint16,uint32 and uint64) The function uses bigInt type convertions previous to values comparison

func IsNumericType

func IsNumericType(x interface{}) bool

IsNumericType checks if an interface's concrete type corresponds to some of golang native numeric types

func MatchesAny

func MatchesAny(search interface{}, items ...interface{}) bool

MatchesAny returns true if any of the given items matches ( equals ) the subject ( search parameter )

func MonthLastDay

func MonthLastDay(year int, month int) int

MonthLastDay returns the last day of month, considering the year for cover february in leap years Month is one-based, then january=1 If month is different of 2 (february) year is ignored Of month is february, year have to be valid

func NameFirstAndLast

func NameFirstAndLast(name string, transformFlags uint) string

NameFirstAndLast returns the first and last words/names from the given input, optionally transformed by transformFlags Example: handy.NameFirstAndLast("friedrich wilhelm nietzsche", handy.TransformFlagTitleCase) // returns "Friedrich Nietzsche"

func NameInitials

func NameInitials(name string, transformFlags uint) string

NameInitials returns the first and last words/names from the given input, optionally transformed by transformFlags

func NowAsString

func NowAsString(format string) string

NowAsString formats time.Now() as string, considering the format directive

func OnlyDigits

func OnlyDigits(sequence string) string

OnlyDigits returns only the numbers from the given string, after strip all the rest ( letters, spaces, etc. )

func OnlyLetters

func OnlyLetters(sequence string) string

OnlyLetters returns only the letters from the given string, after strip all the rest ( numbers, spaces, etc. )

func OnlyLettersAndNumbers

func OnlyLettersAndNumbers(sequence string) string

OnlyLettersAndNumbers returns only the letters and numbers from the given string, after strip all the rest, like spaces and special symbols.

func PositiveOrZero

func PositiveOrZero(n int) int

PositiveOrZero checks if a signed number is negative, and in this case returns zero.

func RandomInt

func RandomInt(min, max int) int

RandomInt returns a random integer within the given (inclusive) range

func RandomIntArray

func RandomIntArray(min, max, howMany int) []int

RandomIntArray returns an array filled with random integer numbers

func RandomReseed

func RandomReseed(min, max int) int

RandomReseed restarts the randonSeeder and returns a random integer within the given (inclusive) range

func RandomString

func RandomString(minLen, maxLen int, allowUnicode, allowNumbers, allowSymbols, allowSpaces bool) string

RandomString generates a string sequence based on given params/rules

func RemoveDigits

func RemoveDigits(sequence string) string

RemoveDigits returns the given string without digit/numeric runes

func Reverse

func Reverse(s string) string

Reverse returns the given string written backwards, with letters reversed.

func RuneHasSymbol

func RuneHasSymbol(ru rune) bool

RuneHasSymbol returns true if the given rune contains a symbol

func StrContainsEmail

func StrContainsEmail(seq string) bool

StrContainsEmail returns true if given string contains an email address

func StringAsDateTime

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

StringAsDateTime formats time.Time variables as strings, considering the format directive

func StringAsFloat

func StringAsFloat(s string, decimalSeparator, thousandsSeparator rune) float64

StringAsFloat tries to convert a string to float, and if it can't, just returns zero It's limited to one billion

func StringAsInteger

func StringAsInteger(s string) int

StringAsInteger returns the integer value extracted from string, or zero

func StringHash

func StringHash(s string) string

StringHash simply generates a SHA256 hash from the given string In case of error, return ""

func StringReplaceAll

func StringReplaceAll(original string, replacementPairs ...string) string

StringReplaceAll keeps replacing until there's no more ocurrences to replace.

func Tif

func Tif(condition bool, tifThen, tifElse interface{}) interface{}

Tif is a simple implementation of the dear ternary IF operator

func Today

func Today() (time.Time, string)

Today returns today's date at zero hours, minutes, seconds, etc. It returns a time and a yyyy-mm-dd formated string

func Todayf

func Todayf(format string) (time.Time, string)

Todayf returns today's date at zero hours, minutes, seconds, etc. It returns a time and a custom formated string

func Transform

func Transform(s string, maxLen int, transformFlags uint) string

Transform handles a string according given flags/parametrization, as follows: The transformations are made in arbitrary order, what can result in unexpected output. It the input matters, use TransformSerially instead. If maxLen==0, truncation is skipped The last operations are, by order, truncation and trimming.

func TransformSerially

func TransformSerially(s string, maxLen int, transformFlags ...uint) string

TransformSerially reformat given string according parameters, in the order these params were sent Example: TransformSerially("uh lalah 123", 4, TransformFlagOnlyDigits,TransformFlagHash,TransformFlagUpperCase)

First remove non-digits, then hashes string and after make it all uppercase.

If maxLen==0, truncation is skipped Truncation is the last operation

func TrimLen

func TrimLen(text string) int

TrimLen returns the runes count after trim the spaces

func Truncate

func Truncate(s string, maxLen int, trim bool) string

Truncate limits the length of a given string, trimming or not, according parameters

func YMD

func YMD() (int, int, int)

YMD returns today's date tokenized as year, month and day of month

func YMDasDate

func YMDasDate(yyyymmdd string) (time.Time, error)

YMDasDate returns a valid time from the given yyymmdd-formatted input

func YMDasDateUTC

func YMDasDateUTC(yyyymmdd string, utc bool) (time.Time, error)

YMDasDateUTC returns a valid UTC time from the given yyymmdd-formatted input

func YearsAge

func YearsAge(birthdate time.Time) int

YearsAge returns the number of years past since a given date

Types

type DateStrCheck

type DateStrCheck uint8
const (
	DateStrCheckOk            DateStrCheck = 0
	DateStrCheckErrInvalid    DateStrCheck = 1
	DateStrCheckErrOutOfRange DateStrCheck = 2
	DateStrCheckErrEmpty      DateStrCheck = 3
)

func DateStrCheckAge

func DateStrCheckAge(date, format string, yearsAgeMin, yearsAgeMax int, acceptEmpty bool) DateStrCheck

DateStrCheckAge checks a date string considering minimum and maximum age The resulting code can be translated to text, according prefered idiom, with DateStrCheckErrMessage

func DateStrCheckRange

func DateStrCheckRange(date, format string, dateMin, dateMax time.Time, acceptEmpty bool) DateStrCheck

DateStrCheckRange checks a date string considering minimum and maximum date range The resulting code can be translated to text, according prefered idiom, with DateStrCheckErrMessage