utils

package
v0.38.3 Latest Latest
Warning

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

Go to latest
Published: May 9, 2019 License: AGPL-3.0 Imports: 22 Imported by: 43

Documentation

Index

Constants

View Source
const (
	DateFormatYearMonthDay DateFormat = "YYYY-MM-DD"
	DateFormatMonthDayYear DateFormat = "MM-DD-YYYY"
	DateFormatDayMonthYear DateFormat = "DD-MM-YYYY"

	TimeFormatHourMinute           TimeFormat = "tt:mm"
	TimeFormatHourMinuteAmPm       TimeFormat = "h:mm aa"
	TimeFormatHourMinuteSecond     TimeFormat = "tt:mm:ss"
	TimeFormatHourMinuteSecondAmPm TimeFormat = "h:mm:ss aa"
)

standard date and time formats

View Source
const (
	LocationPathSeparator = ">"
)

Variables

View Source
var DefaultNumberFormat = &NumberFormat{DecimalSymbol: `.`, DigitGroupingSymbol: `,`}

DefaultNumberFormat is the default number formatting, e.g. 1,234.567

View Source
var DefaultRand = rand.New(rand.NewSource(time.Now().UnixNano()))

DefaultRand is the default rand for calls to Rand()

View Source
var NilCountry = Country("")

NilCountry represents our nil, or unknown country

View Source
var NilLanguage = Language("")

NilLanguage represents our nil, or unknown language

View Source
var Validator = validator.New()

Validator is our system validator, it can be shared across threads

View Source
var ZeroDate = Date{}

ZeroDate is our uninitialized date value

View Source
var ZeroDateTime = time.Time{}

ZeroDateTime is our uninitialized datetime value

View Source
var ZeroTimeOfDay = TimeOfDay{}

ZeroTimeOfDay is our uninitialized time of day value

Functions

func DateTimeFromString added in v0.28.4

func DateTimeFromString(env Environment, str string, fillTime bool) (time.Time, error)

DateTimeFromString returns a datetime constructed from the passed in string, or an error if we are unable to extract one

func DateTimeToISO added in v0.28.4

func DateTimeToISO(date time.Time) string

DateTimeToISO converts the passed in time.Time to a string in ISO8601 format

func DateToUTCRange added in v0.4.0

func DateToUTCRange(d time.Time, tz *time.Location) (time.Time, time.Time)

DateToUTCRange returns the UTC time range of the given day

func DaysBetween

func DaysBetween(date1 time.Time, date2 time.Time) int

DaysBetween returns the number of calendar days (an int) between the two dates. Note that if these are in different timezones then the local calendar day is used for each and the difference is calculated from that.

func DeriveCountryFromTel added in v0.14.7

func DeriveCountryFromTel(number string) string

DeriveCountryFromTel attempts to derive a country code (e.g. RW) from a phone number

func Indent added in v0.34.1

func Indent(s string, prefix string) string

Indent indents each non-empty line in the given string

func IsNil added in v0.4.0

func IsNil(v interface{}) bool

IsNil returns whether the given object is nil or an interface to a nil

func IsPossibleLocationPath added in v0.32.0

func IsPossibleLocationPath(str string) bool

IsPossibleLocationPath returns whether the given string could be a location path

func IsValidJSON added in v0.17.0

func IsValidJSON(data []byte) bool

IsValidJSON determines whether the given bytes contain valid JSON, by trying to parse it

func JSONDecodeGeneric added in v0.23.0

func JSONDecodeGeneric(data []byte) (interface{}, error)

JSONDecodeGeneric decodes the given JSON as a generic map or slice

func JSONMarshal added in v0.9.6

func JSONMarshal(v interface{}) ([]byte, error)

JSONMarshal marshals the given object to JSON

func JSONMarshalPretty added in v0.9.6

func JSONMarshalPretty(v interface{}) ([]byte, error)

JSONMarshalPretty marshals the given object to pretty JSON

func MaxInt added in v0.34.1

func MaxInt(x, y int) int

MaxInt returns the maximum of two integers

func MinInt added in v0.10.1

func MinInt(x, y int) int

MinInt returns the minimum of two integers

func MonthsBetween

func MonthsBetween(date1 time.Time, date2 time.Time) int

MonthsBetween returns the number of calendar months (an int) between the two dates. Note that if these are in different timezones then the local calendar day is used for each and the difference is calculated from that.

func NewSeededRand added in v0.8.0

func NewSeededRand(seed int64) *rand.Rand

NewSeededRand creates a new seeded rand

func Now added in v0.10.20

func Now() time.Time

Now returns the current time

func PrefixOverlap added in v0.14.7

func PrefixOverlap(s1, s2 string) int

PrefixOverlap returns the number of prefix characters which s1 and s2 have in common

func RandDecimal added in v0.8.0

func RandDecimal() decimal.Decimal

RandDecimal returns a random decimal in the range [0.0, 1.0)

func RandIntN added in v0.8.0

func RandIntN(n int) int

RandIntN returns a random integer in the range [0, n)

func ReadTypeFromJSON added in v0.22.0

func ReadTypeFromJSON(data []byte) (string, error)

ReadTypeFromJSON reads a field called `type` from the given JSON

func SetRand added in v0.8.0

func SetRand(rnd *rand.Rand)

SetRand sets the rand used by Rand()

func SetTimeSource added in v0.10.20

func SetTimeSource(source TimeSource)

SetTimeSource sets the time source used by Now()

func SetUUIDGenerator added in v0.6.0

func SetUUIDGenerator(generator UUIDGenerator)

SetUUIDGenerator sets the generator used by UUID4()

func Snakify

func Snakify(text string) string

Snakify turns the passed in string into a context reference. We replace all whitespace characters with _ and replace any duplicate underscores

func StringSliceContains added in v0.30.2

func StringSliceContains(slice []string, str string, caseSensitive bool) bool

StringSliceContains determines whether the given slice of strings contains the given string

func StringSlices added in v0.28.3

func StringSlices(s string, indices []int) []string

StringSlices returns the slices of s defined by pairs of indexes in indices

func ToGoDateFormat

func ToGoDateFormat(format string, mode FormattingMode) (string, error)

ToGoDateFormat converts the passed in format to a GoLang format string.

If mode is DateOnlyFormatting or DateTimeFormatting, the following sequences are accepted:

`YY`        - last two digits of year 0-99
`YYYY`      - four digits of your 0000-9999
`M`         - month 1-12
`MM`        - month 01-12
`D`         - day of month, 1-31
`DD`        - day of month, zero padded 0-31

If mode is TimeOnlyFormatting or DateTimeFormatting, the following sequences are accepted:

`h`         - hour of the day 1-12
`hh`        - hour of the day 01-12
`tt`        - twenty four hour of the day 01-23
`m`         - minute 0-59
`mm`        - minute 00-59
`s`         - second 0-59
`ss`        - second 00-59
`fff`       - milliseconds
`ffffff`    - microseconds
`fffffffff` - nanoseconds
`aa`        - am or pm
`AA`        - AM or PM
`Z`         - hour and minute offset from UTC, or Z for UTC
`ZZZ`       - hour and minute offset from UTC

ignored chars: ' ', ':', ',', 'T', '-', '_', '/'

func TokenizeString

func TokenizeString(str string) []string

TokenizeString returns the words in the passed in string, split by non word characters including emojis

func TokenizeStringByChars added in v0.10.17

func TokenizeStringByChars(str string, chars string) []string

TokenizeStringByChars returns the words in the passed in string, split by the chars in the given string

func UnmarshalAndValidate added in v0.4.0

func UnmarshalAndValidate(data []byte, obj interface{}) error

UnmarshalAndValidate is a convenience function to unmarshal an object and validate it

func UnmarshalAndValidateWithLimit added in v0.13.1

func UnmarshalAndValidateWithLimit(reader io.ReadCloser, s interface{}, limit int64) error

UnmarshalAndValidateWithLimit unmarsmals a struct with a limit on how many bytes can be read from the given reader

func UnmarshalArray added in v0.4.0

func UnmarshalArray(data json.RawMessage) ([]json.RawMessage, error)

UnmarshalArray unmarshals an array of objects from the given JSON

func Validate added in v0.4.0

func Validate(obj interface{}) error

Validate will run validation on the given object and return a set of field specific errors in the format: field <fieldname> <tag specific message>

For example: "field 'flows' is required"

Types

type Attachment added in v0.32.0

type Attachment string

Attachment is a media attachment on a message in the format <content-type>:<url>. Content type may be a full media type or may omit the subtype when it is unknown.

Examples:

func (Attachment) ContentType added in v0.32.0

func (a Attachment) ContentType() string

ContentType returns the MIME type of this attachment

func (Attachment) ToParts added in v0.32.0

func (a Attachment) ToParts() (string, string)

ToParts splits an attachment string into content-type and URL

func (Attachment) URL added in v0.32.0

func (a Attachment) URL() string

URL returns the full URL of this attachment

type Country added in v0.23.0

type Country string

Country is a ISO 3166-1 alpha-2 country code

type Date added in v0.28.4

type Date struct {
	Year  int
	Month time.Month
	Day   int
}

Date is a local gregorian calendar date

func DateFromString

func DateFromString(env Environment, str string) (Date, error)

DateFromString returns a date constructed from the passed in string, or an error if we are unable to extract one

func ExtractDate added in v0.28.4

func ExtractDate(dt time.Time) Date

ExtractDate extracts the date from the give datetime

func NewDate added in v0.28.4

func NewDate(year, month, day int) Date

NewDate creates a new date

func ParseDate added in v0.28.4

func ParseDate(layout string, value string) (Date, error)

ParseDate parses the given string into a date

func (Date) Combine added in v0.28.4

func (d Date) Combine(timeOfDay TimeOfDay, tz *time.Location) time.Time

Combine combines this date and a time to make a datetime

func (Date) Compare added in v0.28.4

func (d Date) Compare(other Date) int

Compare compares this time of day to another

func (Date) Equal added in v0.28.4

func (d Date) Equal(other Date) bool

Equal determines equality for this type

func (Date) Format added in v0.28.4

func (d Date) Format(layout string) string

Format formats this date as a string

func (Date) String added in v0.28.4

func (d Date) String() string

String returns the ISO8601 representation

func (Date) Weekday added in v0.28.4

func (d Date) Weekday() time.Weekday

Weekday returns the day of the week

type DateFormat

type DateFormat string

DateFormat a date format string

func (DateFormat) String

func (df DateFormat) String() string

type Environment

type Environment interface {
	DateFormat() DateFormat
	TimeFormat() TimeFormat
	Timezone() *time.Location
	DefaultLanguage() Language
	AllowedLanguages() []Language
	DefaultCountry() Country
	NumberFormat() *NumberFormat
	RedactionPolicy() RedactionPolicy
	MaxValueLength() int

	// Convenience method to get the current time in the env timezone
	Now() time.Time

	// extensions to the engine can expect their own env values
	Extension(string) json.RawMessage

	Equal(Environment) bool
}

Environment defines the environment that the Excellent function is running in, this includes the timezone the user is in as well as the preferred date and time formats.

func ReadEnvironment added in v0.4.0

func ReadEnvironment(data json.RawMessage) (Environment, error)

ReadEnvironment reads an environment from the given JSON

type EnvironmentBuilder added in v0.27.2

type EnvironmentBuilder struct {
	// contains filtered or unexported fields
}

EnvironmentBuilder is a builder for environments

func NewEnvironmentBuilder added in v0.27.2

func NewEnvironmentBuilder() *EnvironmentBuilder

NewEnvironmentBuilder creates a new environment builder

func (*EnvironmentBuilder) Build added in v0.27.2

func (b *EnvironmentBuilder) Build() Environment

Build returns the final environment

func (*EnvironmentBuilder) WithAllowedLanguages added in v0.27.2

func (b *EnvironmentBuilder) WithAllowedLanguages(allowedLanguages []Language) *EnvironmentBuilder

func (*EnvironmentBuilder) WithDateFormat added in v0.27.2

func (b *EnvironmentBuilder) WithDateFormat(dateFormat DateFormat) *EnvironmentBuilder

WithDateFormat sets the date format

func (*EnvironmentBuilder) WithDefaultCountry added in v0.27.2

func (b *EnvironmentBuilder) WithDefaultCountry(defaultCountry Country) *EnvironmentBuilder

func (*EnvironmentBuilder) WithDefaultLanguage added in v0.27.2

func (b *EnvironmentBuilder) WithDefaultLanguage(defaultLanguage Language) *EnvironmentBuilder

func (*EnvironmentBuilder) WithMaxValueLength added in v0.27.2

func (b *EnvironmentBuilder) WithMaxValueLength(maxValueLength int) *EnvironmentBuilder

func (*EnvironmentBuilder) WithNumberFormat added in v0.27.2

func (b *EnvironmentBuilder) WithNumberFormat(numberFormat *NumberFormat) *EnvironmentBuilder

func (*EnvironmentBuilder) WithRedactionPolicy added in v0.27.2

func (b *EnvironmentBuilder) WithRedactionPolicy(redactionPolicy RedactionPolicy) *EnvironmentBuilder

func (*EnvironmentBuilder) WithTimeFormat added in v0.27.2

func (b *EnvironmentBuilder) WithTimeFormat(timeFormat TimeFormat) *EnvironmentBuilder

WithTimeFormat sets the time format

func (*EnvironmentBuilder) WithTimezone added in v0.27.2

func (b *EnvironmentBuilder) WithTimezone(timezone *time.Location) *EnvironmentBuilder

type FormattingMode added in v0.10.19

type FormattingMode int

FormattingMode describe a mode of formatting dates, times, datetimes

const (
	DateOnlyFormatting FormattingMode = iota
	TimeOnlyFormatting
	DateTimeFormatting
)

supported formatting modes

type HTTPClient added in v0.9.2

type HTTPClient struct {
	// contains filtered or unexported fields
}

HTTPClient is a client for HTTP requests

func NewHTTPClient added in v0.8.0

func NewHTTPClient(defaultUserAgent string) *HTTPClient

NewHTTPClient creates a new HTTP client with our default options

func (*HTTPClient) Do added in v0.9.2

func (c *HTTPClient) Do(request *http.Request) (*http.Response, error)

Do does the given HTTP request

func (*HTTPClient) DoWithDump added in v0.9.2

func (c *HTTPClient) DoWithDump(request *http.Request) (*http.Response, string, error)

DoWithDump does the given HTTP request and returns a dump of the entire request

func (*HTTPClient) MockWithDump added in v0.10.3

func (c *HTTPClient) MockWithDump(request *http.Request, mockStatus int, mockResponse string) (*http.Response, string, error)

MockWithDump mocks the given HTTP request and returns a dump of the entire request

type Language

type Language string

Language is our internal representation of a language

func ParseLanguage

func ParseLanguage(lang string) (Language, error)

ParseLanguage returns a new Language for the passed in language string, or an error if not found

type Location added in v0.4.0

type Location struct {
	// contains filtered or unexported fields
}

Location represents a single Location

func NewLocation added in v0.4.0

func NewLocation(level LocationLevel, name string) *Location

NewLocation creates a new location object

func (*Location) Aliases added in v0.4.0

func (l *Location) Aliases() []string

Aliases gets the aliases of this location

func (*Location) Children added in v0.4.0

func (l *Location) Children() []*Location

Children gets the children of this location

func (*Location) Level added in v0.4.0

func (l *Location) Level() LocationLevel

Level gets the level of this location

func (*Location) Name added in v0.4.0

func (l *Location) Name() string

Name gets the name of this location

func (*Location) Parent added in v0.4.0

func (l *Location) Parent() *Location

Parent gets the parent of this location

func (*Location) Path added in v0.9.6

func (l *Location) Path() LocationPath

Path gets the full path of this location

func (*Location) String added in v0.9.6

func (l *Location) String() string

type LocationHierarchy added in v0.4.0

type LocationHierarchy struct {
	// contains filtered or unexported fields
}

LocationHierarchy is a hierarical tree of locations

func NewLocationHierarchy added in v0.4.0

func NewLocationHierarchy(root *Location, numLevels int) *LocationHierarchy

NewLocationHierarchy cretes a new location hierarchy

func ReadLocationHierarchy added in v0.4.0

func ReadLocationHierarchy(data json.RawMessage) (*LocationHierarchy, error)

ReadLocationHierarchy reads a location hierarchy from the given JSON

func (*LocationHierarchy) FindByName added in v0.4.0

func (h *LocationHierarchy) FindByName(name string, level LocationLevel, parent *Location) []*Location

FindByName looks for all locations in the hierarchy with the given level and name or alias

func (*LocationHierarchy) FindByPath added in v0.9.6

func (h *LocationHierarchy) FindByPath(path LocationPath) *Location

FindByPath looks for a location in the hierarchy with the given path

func (*LocationHierarchy) Root added in v0.6.0

func (h *LocationHierarchy) Root() *Location

Root gets the root location of this hierarchy (typically a country)

func (*LocationHierarchy) UnmarshalJSON added in v0.22.0

func (h *LocationHierarchy) UnmarshalJSON(data []byte) error

type LocationLevel added in v0.4.0

type LocationLevel int

LocationLevel is a numeric level, e.g. 0 = country, 1 = state

type LocationPath added in v0.32.0

type LocationPath string

LocationPath is a location described by a path Country > State ...

func NewLocationPath added in v0.32.0

func NewLocationPath(parts ...string) LocationPath

func (LocationPath) Name added in v0.32.0

func (p LocationPath) Name() string

Name returns the name of the location referenced

func (LocationPath) Normalize added in v0.32.0

func (p LocationPath) Normalize() LocationPath

Normalize normalizes this location path

type NumberFormat added in v0.21.2

type NumberFormat struct {
	DecimalSymbol       string `json:"decimal_symbol"`
	DigitGroupingSymbol string `json:"digit_grouping_symbol"`
}

NumberFormat describes how numbers should be parsed and formatted

type RedactionPolicy added in v0.10.5

type RedactionPolicy string
const (
	RedactionPolicyNone RedactionPolicy = "none"
	RedactionPolicyURNs RedactionPolicy = "urns"
)

type TimeFormat

type TimeFormat string

TimeFormat a time format string

func (TimeFormat) String

func (tf TimeFormat) String() string

type TimeOfDay added in v0.28.0

type TimeOfDay struct {
	Hour   int
	Minute int
	Second int
	Nanos  int
}

TimeOfDay represents a local time of day value

func ExtractTimeOfDay added in v0.28.0

func ExtractTimeOfDay(dt time.Time) TimeOfDay

ExtractTimeOfDay extracts the time of day from the give datetime

func NewTimeOfDay added in v0.28.0

func NewTimeOfDay(hour, minute, second, nanos int) TimeOfDay

NewTimeOfDay creates a new time of day

func ParseTimeOfDay added in v0.28.0

func ParseTimeOfDay(layout string, value string) (TimeOfDay, error)

ParseTimeOfDay parses the given string into a time of day

func TimeFromString added in v0.28.0

func TimeFromString(str string) (TimeOfDay, error)

TimeFromString returns a time of day constructed from the passed in string, or an error if we are unable to extract one

func (TimeOfDay) Combine added in v0.28.4

func (t TimeOfDay) Combine(date Date, tz *time.Location) time.Time

Combine combines this time and a date to make a datetime

func (TimeOfDay) Compare added in v0.28.0

func (t TimeOfDay) Compare(other TimeOfDay) int

Compare compares this time of day to another

func (TimeOfDay) Equal added in v0.28.3

func (t TimeOfDay) Equal(other TimeOfDay) bool

Equal determines equality for this type

func (TimeOfDay) Format added in v0.28.0

func (t TimeOfDay) Format(layout string) string

Format formats this time of day as a string

func (TimeOfDay) String added in v0.28.0

func (t TimeOfDay) String() string

String returns the ISO8601 representation

type TimeSource added in v0.10.20

type TimeSource interface {
	Now() time.Time
}

TimeSource is something that can provide a time

var DefaultTimeSource TimeSource = defaultTimeSource{}

DefaultTimeSource is the default time source

func NewFixedTimeSource added in v0.10.20

func NewFixedTimeSource(now time.Time) TimeSource

NewFixedTimeSource creates a new fixed time source

func NewSequentialTimeSource added in v0.10.20

func NewSequentialTimeSource(start time.Time) TimeSource

NewSequentialTimeSource creates a new sequential time source

type Typed

type Typed interface {
	Type() string
}

Typed is an interface of objects that are marshalled as typed envelopes

type TypedEnvelope

type TypedEnvelope struct {
	Type string `json:"type" validate:"required"`
}

TypedEnvelope can be mixed into envelopes that have a type field

type UUID added in v0.6.0

type UUID string

UUID is a 36 character UUID

func NewUUID added in v0.6.0

func NewUUID() UUID

NewUUID returns a new NewUUID

type UUIDGenerator added in v0.6.0

type UUIDGenerator interface {
	Next() UUID
}

UUIDGenerator is something that can generate a UUID

var DefaultUUIDGenerator UUIDGenerator = defaultUUID4Generator{}

DefaultUUIDGenerator is the default generator for calls to NewUUID

func NewSeededUUID4Generator added in v0.6.0

func NewSeededUUID4Generator(seed int64) UUIDGenerator

NewSeededUUID4Generator creates a new SeededUUID4Generator from the given seed

type ValidationErrors added in v0.4.0

type ValidationErrors []error

ValidationErrors combines multiple validation errors as a single error

func (ValidationErrors) Error added in v0.4.0

func (e ValidationErrors) Error() string

Error returns a string representation of these validation errors

Jump to

Keyboard shortcuts

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