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
- func AmountAsWord(n int64) string
- func ArrayDifference(a, b []int) []int
- func ArrayDifferenceAtoB(a, b []int) []int
- func Between(n, low, high int) bool
- func Bit(x interface{}) uint8
- func Boolean(x interface{}) bool
- func CheckCNPJ(cnpj string) bool
- func CheckCPF(cpf string) bool
- func CheckDate(format, dateTime string) bool
- func CheckDateYMD(yyyymmdd string) bool
- func CheckEmail(email string) bool
- func CheckMinLen(value string, minLength int) bool
- func CheckNewPassword(password, passwordConfirmation string, minimumlength uint, ...) uint8
- func CheckNewPasswordResult(idiom string, r uint8) string
- func CheckPersonName(name string, acceptEmpty bool) uint8
- func CheckPersonNameResult(idiom string, r uint8) string
- func CheckPhone(phone string, acceptEmpty bool) bool
- func CheckStr(seq string, minLen, maxLen uint, rules uint64) int8
- func CleanSpaces(s string) string
- func DateReformat(dt1 string, currentFormat, newFormat string) string
- func DateStrCheckErrMessage(idiom string, errCode DateStrCheck) string
- func DateTimeAsString(dt time.Time, format string) string
- func DedupSpaces(s string) string
- func ElapsedMonths(from, to time.Time) int
- func ElapsedTime(dtx, dty time.Time) (int, int, int, int, int, int)
- func ElapsedYears(from, to time.Time) int
- func HTTPAnswerJSON(w http.ResponseWriter, data interface{}) error
- func HTTPJSONBodyToStruct(r *http.Request, targetStruct interface{}) bool
- func HTTPJSONToStruct(r *http.Request, targetStruct interface{}, closeBody bool) error
- func HTTPRequestAsFloat64(r *http.Request, key string, decimalSeparator rune) float64
- func HTTPRequestAsInteger(r *http.Request, key string) int
- func HTTPRequestAsString(r *http.Request, key string, maxLength int, transformOptions ...uint) string
- func HasLetter(s string) bool
- func HasNumber(s string) bool
- func HasOnlyLetters(sequence string) bool
- func HasOnlyNumbers(sequence string) bool
- func HasSymbol(s string) bool
- func InArray(array interface{}, item interface{}) bool
- func InArrayIntFlex(item interface{}, array interface{}) bool
- func IsNumericType(x interface{}) bool
- func MatchesAny(search interface{}, items ...interface{}) bool
- func MonthLastDay(year int, month int) int
- func NameFirstAndLast(name string, transformFlags uint) string
- func NameInitials(name string, transformFlags uint) string
- func NowAsString(format string) string
- func OnlyDigits(sequence string) string
- func OnlyLetters(sequence string) string
- func OnlyLettersAndNumbers(sequence string) string
- func PositiveOrZero(n int) int
- func RandomInt(min, max int) int
- func RandomIntArray(min, max, howMany int) []int
- func RandomReseed(min, max int) int
- func RandomString(minLen, maxLen int, allowUnicode, allowNumbers, allowSymbols, allowSpaces bool) string
- func RemoveDigits(sequence string) string
- func Reverse(s string) string
- func RuneHasSymbol(ru rune) bool
- func StrContainsEmail(seq string) bool
- func StringAsDateTime(s string, format string) time.Time
- func StringAsFloat(s string, decimalSeparator, thousandsSeparator rune) float64
- func StringAsInteger(s string) int
- func StringHash(s string) string
- func StringReplaceAll(original string, replacementPairs ...string) string
- func Tif(condition bool, tifThen, tifElse interface{}) interface{}
- func Today() (time.Time, string)
- func Todayf(format string) (time.Time, string)
- func Transform(s string, maxLen int, transformFlags uint) string
- func TransformSerially(s string, maxLen int, transformFlags ...uint) string
- func TrimLen(text string) int
- func Truncate(s string, maxLen int, trim bool) string
- func YMD() (int, int, int)
- func YMDasDate(yyyymmdd string) (time.Time, error)
- func YMDasDateUTC(yyyymmdd string, utc bool) (time.Time, error)
- func YearsAge(birthdate time.Time) int
- type DateStrCheck
Constants ¶
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 )
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 )
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 )
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 ¶
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 ¶
ArrayDifference returns all items that doesn't exist in both given arrays
func ArrayDifferenceAtoB ¶
ArrayDifferenceAtoB returns the items from A that doesn't exist in B
func Between ¶
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 ¶
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 ¶
CheckCPF returns true if the given input is a valid cpf CPF is the Brazilian TAXPayerID document for persons
func CheckDate ¶
CheckDate validates a date using the given format
func CheckDateYMD ¶
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 ¶
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 ¶
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 ¶
CheckNewPasswordResult returns a meaningful message describing the code generated bu CheckNewPassword() The routine considers the given idiom. The fallback is in english
func CheckPersonName ¶
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 ¶
CheckPersonNameResult returns a meaningful message describing the code generated bu CheckPersonName The routine considers the given idiom. The fallback is in english
func CheckPhone ¶
CheckPhone returns true if a given input has between 9 and 14 digits
func CheckStr ¶
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 ¶
CleanSpaces removes duplicated spaces, tabs and newLine characters and then trim string's both sides
func DateReformat ¶
DateReformat gets a date string in a given currentFormat, and transform it according newFormat
func DateStrCheckErrMessage ¶ added in v1.1.18
func DateStrCheckErrMessage(idiom string, errCode DateStrCheck) string
func DateTimeAsString ¶
DateTimeAsString formats time.Time variables as strings, considering the format directive
func DedupSpaces ¶
DedupSpaces removes duplicated spaces, tabs and newLine characters I.E: Replaces two tabs for one single tab
func ElapsedMonths ¶
ElapsedMonths returns the number of elapsed months between two given dates
func ElapsedTime ¶
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 ¶
ElapsedYears returns the number of elapsed years between two given dates
func HTTPAnswerJSON ¶ added in v1.1.4
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 ¶
HTTPJSONBodyToStruct decode json to a given anatomically compatible struct THIS ROUTINE IS BEEN DEPRECATED. Use HTTPJSONToStruct() instead.
func HTTPJSONToStruct ¶
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 ¶
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 ¶
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 ¶
HasLetter returns true if input string contains at least one letter
func HasNumber ¶
HasNumber returns true if input string contains at least one digit/number
func HasOnlyLetters ¶
HasOnlyLetters returns true if the input is entirely composed by letters
func HasOnlyNumbers ¶
HasOnlyNumbers returns true if the input is entirely numeric
func HasSymbol ¶
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 ¶
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 ¶
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 ¶
NameInitials returns the first and last words/names from the given input, optionally transformed by transformFlags
func NowAsString ¶
NowAsString formats time.Now() as string, considering the format directive
func OnlyDigits ¶
OnlyDigits returns only the numbers from the given string, after strip all the rest ( letters, spaces, etc. )
func OnlyLetters ¶
OnlyLetters returns only the letters from the given string, after strip all the rest ( numbers, spaces, etc. )
func OnlyLettersAndNumbers ¶
OnlyLettersAndNumbers returns only the letters and numbers from the given string, after strip all the rest, like spaces and special symbols.
func PositiveOrZero ¶
PositiveOrZero checks if a signed number is negative, and in this case returns zero.
func RandomInt ¶
RandomInt returns a random integer within the given (inclusive) range
func RandomIntArray ¶
RandomIntArray returns an array filled with random integer numbers
func RandomReseed ¶
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 ¶
RemoveDigits returns the given string without digit/numeric runes
func Reverse ¶
Reverse returns the given string written backwards, with letters reversed.
func RuneHasSymbol ¶
RuneHasSymbol returns true if the given rune contains a symbol
func StrContainsEmail ¶
StrContainsEmail returns true if given string contains an email address
func StringAsDateTime ¶
StringAsDateTime formats time.Time variables as strings, considering the format directive
func StringAsFloat ¶
StringAsFloat tries to convert a string to float, and if it can't, just returns zero It's limited to one billion
func StringAsInteger ¶
StringAsInteger returns the integer value extracted from string, or zero
func StringHash ¶
StringHash simply generates a SHA256 hash from the given string In case of error, return ""
func StringReplaceAll ¶
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 ¶
Today returns today's date at zero hours, minutes, seconds, etc. It returns a time and a yyyy-mm-dd formated string
func Todayf ¶
Todayf returns today's date at zero hours, minutes, seconds, etc. It returns a time and a custom formated string
func Transform ¶
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 ¶
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 Truncate ¶
Truncate limits the length of a given string, trimming or not, according parameters
func YMD ¶
YMD returns today's date tokenized as year, month and day of month
func YMDasDate ¶
YMDasDate returns a valid time from the given yyymmdd-formatted input
func YMDasDateUTC ¶
YMDasDateUTC returns a valid UTC time from the given yyymmdd-formatted input
Types ¶
type DateStrCheck ¶ added in v1.1.18
type DateStrCheck uint8
const ( DateStrCheckOk DateStrCheck = 0 DateStrCheckErrInvalid DateStrCheck = 1 DateStrCheckErrOutOfRange DateStrCheck = 2 DateStrCheckErrEmpty DateStrCheck = 3 )
func DateStrCheckAge ¶ added in v1.1.18
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 ¶ added in v1.1.18
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