handy: github.com/miguelpragier/handy Index | Files

package handy

import "github.com/miguelpragier/handy"

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.


Package Files

handy.go handybra.go handydatetime.go handyhttp.go handyinarray.go handytranslations.go


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 = uint8(1)
    // TransformFlagTrim Trim spaces before and after process the input
    // TransformFlagTrim Trims the string, removing leading and trailing spaces
    TransformFlagTrim = uint8(2)
    // TransformFlagLowerCase Makes the string lowercase
    // If it's combined with TransformFlagUpperCase, only uppercase remains, once is executed later.
    TransformFlagLowerCase = uint8(4)
    // TransformFlagUpperCase Makes the string uppercase
    // If it's combined with TransformFlagLowerCase, only uppercase remains, once it's executed later.
    TransformFlagUpperCase = uint8(8)
    // TransformFlagOnlyDigits Removes all non-numeric characters
    TransformFlagOnlyDigits = uint8(16)
    // TransformFlagOnlyLetters Removes all non-letter characters
    TransformFlagOnlyLetters = uint8(32)
    // TransformFlagOnlyLettersAndDigits Leaves only letters and numbers
    TransformFlagOnlyLettersAndDigits = uint8(64)
    // TransformFlagHash After process all other flags, applies SHA256 hashing on string for output
    // 	The routine applies handy.StringHash() on given string
    TransformFlagHash = uint8(128)
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

func AmountAsWord Uses

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 Uses

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

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

func ArrayDifferenceAtoB Uses

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

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

func Between Uses

func Between(n, low, high int) bool

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

func Bit Uses

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 Uses

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 Uses

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 Uses

func CheckCPF(cpf string) bool

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

func CheckDate Uses

func CheckDate(format, dateTime string) bool

CheckDate validates a date using the given format

func CheckDateYMD Uses

func CheckDateYMD(yyyymmdd string) bool

CheckDateYMD returns true if given sequence 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 Uses

func CheckEmail(email string) bool

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 CheckMinLen Uses

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 Uses

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 Uses

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 Uses

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 Uses

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 Uses

func CheckPhone(phone string, acceptEmpty bool) bool

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

func DateTimeAsString Uses

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

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

func ElapsedMonths Uses

func ElapsedMonths(from, to time.Time) int

ElapsedMonths returns the number of elapsed months between two given dates

func ElapsedYears Uses

func ElapsedYears(from, to time.Time) int

ElapsedYears returns the number of elapsed years between two given dates

func HTTPJSONBodyToStruct Uses

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

HTTPJSONBodyToStruct decode json to a given anatomically compatible struct

func HTTPRequestAsFloat64 Uses

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 Uses

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 Uses

func HTTPRequestAsString(r *http.Request, key string, maxLength int, transformOptions ...uint8) 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 HasOnlyLetters Uses

func HasOnlyLetters(sequence string) bool

HasOnlyLetters returns true if the sequence is entirely composed by letters

func HasOnlyNumbers Uses

func HasOnlyNumbers(sequence string) bool

HasOnlyNumbers returns true if the sequence is entirely numeric

func InArray Uses

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 IsNumericType Uses

func IsNumericType(x interface{}) bool

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

func MatchesAny Uses

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

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

func MonthLastDay Uses

func MonthLastDay(year int, month int) int

MonthLastDay returns the last day of month, considering the year for cover february in leap years

func NowAsString Uses

func NowAsString(format string) string

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

func OnlyDigits Uses

func OnlyDigits(sequence string) string

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

func OnlyLetters Uses

func OnlyLetters(sequence string) string

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

func OnlyLettersAndNumbers Uses

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 RandomInt Uses

func RandomInt(min, max int) int

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

func RandomReseed Uses

func RandomReseed(min, max int) int

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

func Reverse Uses

func Reverse(s string) string

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

func RuneHasSymbol Uses

func RuneHasSymbol(ru rune) bool

RuneHasSymbol returns true if the given rune contains a symbol

func StringAsDateTime Uses

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

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

func StringAsFloat Uses

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 Uses

func StringAsInteger(s string) int

StringAsInteger returns the integer value extracted from string, or zero

func StringHash Uses

func StringHash(s string) string

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

func StringReplaceAll Uses

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

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

func Tif Uses

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

Tif is a simple implementation of the dear ternary IF operator

func Today Uses

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 Uses

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 Uses

func Transform(s string, maxLen int, transformFlags uint8) 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 sequence matters, use TransformSerially instead. If maxLen==0, truncation is skipped The last operations are, by order, truncation and trimming.

func TransformSerially Uses

func TransformSerially(s string, maxLen int, transformFlags ...uint8) 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 Uses

func TrimLen(text string) int

TrimLen returns the runes count after trim the spaces

func Truncate Uses

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

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

func YMD Uses

func YMD() (int, int, int)

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

func YMDasDate Uses

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

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

func YMDasDateUTC Uses

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

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

func YearsAge Uses

func YearsAge(birthdate time.Time) int

YearsAge returns the number of years past since a given date

Package handy imports 13 packages (graph). Updated 2019-06-16. Refresh now. Tools for package owners.