Documentation
¶
Index ¶
- Variables
- func AnyTo[T any](v any) any
- func As[T any](v any) (T, error)
- func Bool(value any) (bool, error)
- func Build[T any](t T, builders ...Builder[T]) (T, error)
- func Bytes(value any) ([]byte, error)
- func DataTypeConvert(dt DataType, value any) (any, error)
- func DataTypeNames() []string
- func Date(value any) (time.Time, error)
- func Defer(err *error, errs ...error)
- func DeferCall(err *error, fn func() error)
- func DeferCloser(err *error, closer io.Closer)
- func DeferCloserToGroup(c **CloserGroup, closer ...io.Closer) io.Closer
- func Dereference[T any](t *T) T
- func ErrorGroupFormatterDefault(errors []Error) string
- func ErrorKey(namespace, code string) string
- func FakeStrategyNames() []string
- func Float32(value any) (float32, error)
- func Float64(value any) (float64, error)
- func Int16(value any) (int16, error)
- func Int32(value any) (int32, error)
- func Int64(value any) (int64, error)
- func Int8(value any) (int8, error)
- func IsZero[T any](t T) bool
- func IsZeroAny(t any) bool
- func MapFilter[K comparable, V any](input map[K]V, predicate KeyedPredicate[K, V]) map[K]V
- func MapFilterRange[K comparable, V any](input KeyedRanger[K, V], predicate KeyedPredicate[K, V]) map[K]V
- func MapKeys[K comparable, V any](input map[K]V) []K
- func MapValues[K comparable, V any](input map[K]V) []V
- func Must[T any](t T) T
- func MustBool[T any](value T) bool
- func MustDuration[T any](value T) time.Duration
- func MustE[T any](fn func() (T, error)) T
- func MustInt[T any](value T) int
- func MustMapAny[T any](value T) map[string]any
- func MustMapString[T any](value T) map[string]string
- func MustString[T any](value T) string
- func MustT[T any](v any) T
- func MustTime[T any](value T) time.Time
- func Null(value any) (any, error)
- func OptionApply[T any](t T, options ...Option[T]) (T, error)
- func Pointer[T any](t T) *T
- func RandomExcluding[T comparable](fn func() T, exclude map[T]struct{}) T
- func RandomNumber[T constraints.Integer | constraints.Float](r *Random) T
- func RandomNumberRange[T constraints.Integer | constraints.Float](r *Random, min, max T) T
- func RandomRegex[T ~string](r *Random, pattern string) T
- func RandomSelection[T any](r *Random, items []T) T
- func RandomString[T ~string](r *Random, min, max uint64) T
- func ReturnGlobal(random *Random)
- func SafeDereference[T any](t *T) T
- func SliceFilter[T any](input []T, predicate Predicate[T]) []T
- func SliceFilterRange[T any](input Ranger[T], predicate Predicate[T]) []T
- func SliceFlatten[T any](input ...[]T) []T
- func SliceMap[TIn any, TOut any](input []TIn, mapper Mapper[TIn, TOut]) []TOut
- func SliceSet[T comparable](input []T) map[T]struct{}
- func SliceToMap[K comparable, V any](input []V, key func(v V) K) map[K]V
- func SliceTypeAssert[TIn any, TOut any](input []TIn) []TOut
- func Task(ctx context.Context, task TaskFn, options ...Option[*TaskConfig]) error
- func Timestamp(value any) (time.Time, error)
- func TimestampMs(value any) (time.Time, error)
- func TimestampS(value any) (time.Time, error)
- func TitleCase(s string) string
- func ToBool[T any](value T) (bool, error)
- func ToDuration[T any](value T) (time.Duration, error)
- func ToInt[T any](value T) (int, error)
- func ToMapAny[T any](value T) (map[string]any, error)
- func ToMapString[T any](value T) (map[string]string, error)
- func ToString[T any](value T) (string, error)
- func ToTime[T any](value T) (time.Time, error)
- func URLPort(u *url.URL) (int, error)
- func Uint16(value any) (uint16, error)
- func Uint32(value any) (uint32, error)
- func Uint64(value any) (uint64, error)
- func Uint8(value any) (uint8, error)
- func Utf8(value any) (string, error)
- func ZeroPad[T constraints.Integer](width T, v T) string
- type Bitmask
- type Builder
- type Causer
- type CloserFn
- type CloserGroup
- type ContextKey
- type DataType
- type DebugExtras
- type Error
- func (e Error) AsGroup() *ErrorGroup
- func (e Error) Copy() Error
- func (e Error) Equal(e2 Error) bool
- func (e Error) Error() string
- func (e Error) Format(s fmt.State, verb rune)
- func (e Error) Is(target error) bool
- func (e Error) IsRetryable() bool
- func (e Error) IsTimeout() bool
- func (e Error) IsTransient() bool
- func (e Error) IsZero() bool
- func (e Error) Key() string
- func (e Error) String() string
- func (e Error) Unwrap() error
- func (e Error) WithDebugInfo(extras DebugExtras) Error
- func (e Error) WithFlag(attribute Bitmask) Error
- func (e Error) WithHelp(extras HelpExtras) Error
- func (e Error) WithRetry(extras RetryExtras) Error
- func (e Error) WithTag(tags ...string) Error
- func (e Error) Wrap(err error) Error
- func (e Error) Wrapf(format string, a ...any) Error
- type ErrorExtras
- type ErrorGroup
- func (g *ErrorGroup) Append(errs ...error)
- func (g *ErrorGroup) Empty() bool
- func (g *ErrorGroup) Error() string
- func (g *ErrorGroup) ErrorOrNil() error
- func (g *ErrorGroup) GroupOrNil() *ErrorGroup
- func (g *ErrorGroup) Len() int
- func (g *ErrorGroup) Less(i, j int) bool
- func (g *ErrorGroup) Slice() []Error
- func (g *ErrorGroup) Swap(i, j int)
- func (g *ErrorGroup) Translate(translate ErrorTranslate)
- func (g *ErrorGroup) Unwrap() error
- type ErrorGroupFormatter
- type ErrorTranslate
- type FakeConstraintsNumeric
- type FakeConstraintsTextual
- type FakeNumber
- type FakeRequest
- type FakeState
- type FakeStrategy
- type FakeText
- type HasAs
- type HasIs
- type HasUnwrap
- type HelpExtras
- type KeyedMapper
- type KeyedPredicate
- type KeyedRanger
- type Link
- type ListType
- type Mapper
- type Memoize
- type Option
- type Optional
- type Predicate
- type Random
- type Ranger
- type RetryExtras
- type TaskCancelFn
- type TaskConfig
- type TaskFn
- type Valid
- type Validator
- type Zeroer
Constants ¶
This section is empty.
Variables ¶
var ( // DefaultTaskTimeout is the default timeout for a task to run. DefaultTaskTimeout = 30 * time.Second // DefaultCancelFn is the default cancel function for a task. DefaultCancelFn = func(context.Context) error { return nil } // DefaultCancelTimeout is the default timeout for a task cancel fn to run. DefaultCancelTimeout = 5 * time.Second )
var ErrConversionNotSupported = Error{
Code: "conversion_not_supported",
Message: "data type could not be converted safety",
Namespace: "com.github.ahawker.stdlib",
}
var ErrInvalidDataType = fmt.Errorf("not a valid DataType, try [%s]", strings.Join(_DataTypeNames, ", "))
var ErrInvalidFakeStrategy = fmt.Errorf("not a valid FakeStrategy, try [%s]", strings.Join(_FakeStrategyNames, ", "))
var ErrPrecisionLoss = Error{
Code: "precision_loss",
Message: "data type could not be converted without loss of precision",
Namespace: "com.github.ahawker.stdlib",
}
var ErrTaskTimeout = Error{ Code: "task_timeout", Message: "task reached its timeout and was cancelled", Namespace: ErrorNamespaceDefault, }
ErrTaskTimeout is returned when a task reaches its timeout cancelled.
var ErrTypeAssertionFailed = Error{ Code: "type_assertion_failed", Message: "type assertion failed", Namespace: ErrorNamespaceDefault, }
ErrTypeAssertionFailed is returned when attempting to type assert a value that cannot be converted.
var ErrTypeConversionFailed = Error{ Code: "type_conversion_failed", Message: "type conversion failed", Namespace: ErrorNamespaceDefault, }
ErrTypeConversionFailed is returned when attempting a type conversion that cannot be performed.
var ErrUndefined = Error{ Code: "undefined", Flags: ErrorFlagUnknown, Message: "wrapped the following error which is not well-defined", Namespace: ErrorNamespaceDefault, }
ErrUndefined indicates the wrapped error is not well-known or previously defined. This likely means it's coming from an external system/library and not a domain error.
var TimestampLayouts = [3]string{ time.Layout, time.RFC3339, time.RFC3339Nano, }
Functions ¶
func AnyTo ¶ added in v1.32.0
AnyTo converts an any interface value to a value that can be type asserted to type T.
func As ¶ added in v1.33.0
As performs a type assertion of 'any' value to type T. If it fails an error is returned.
func Build ¶ added in v1.17.0
Build applies all functional builders to type t and returns the type built.
func DataTypeNames ¶ added in v1.53.0
func DataTypeNames() []string
DataTypeNames returns a list of possible string values of DataType.
func DeferCall ¶ added in v1.29.0
DeferCall is a helper for deferring a function call (closer) that can return an error when in a function context that can return multiple errors.
func DeferCloser ¶ added in v1.28.0
DeferCloser is a helper for deferring a io.Closer that can return an error when in a function context that can return multiple errors.
func DeferCloserToGroup ¶ added in v1.51.0
func DeferCloserToGroup(c **CloserGroup, closer ...io.Closer) io.Closer
DeferCloserToGroup is a helper for deferring a closer to a group.
func Dereference ¶ added in v1.54.0
func Dereference[T any](t *T) T
Dereference dereference the given pointer.
func ErrorGroupFormatterDefault ¶
ErrorGroupFormatterDefault is a basic Formatter that outputs the number of errors that occurred along with a bullet point list of the errors.
func ErrorKey ¶ added in v1.27.0
ErrorKey returns a slug that should be unique for each error (namespace + code).
func FakeStrategyNames ¶ added in v1.42.0
func FakeStrategyNames() []string
FakeStrategyNames returns a list of possible string values of FakeStrategy.
func IsZeroAny ¶ added in v1.19.0
IsZeroAny returns true if the given value is equal to the zero value of the type.
func MapFilter ¶
func MapFilter[K comparable, V any](input map[K]V, predicate KeyedPredicate[K, V]) map[K]V
MapFilter will return a new map containing only items from the input map that match the predicate function.
func MapFilterRange ¶
func MapFilterRange[K comparable, V any](input KeyedRanger[K, V], predicate KeyedPredicate[K, V]) map[K]V
MapFilterRange will return a new map containing only items from the input keyed ranger that match the predicate function.
func MapKeys ¶ added in v1.23.0
func MapKeys[K comparable, V any](input map[K]V) []K
MapKeys returns a slice of all keys for the map.
func MapValues ¶ added in v1.23.0
func MapValues[K comparable, V any](input map[K]V) []V
MapValues returns a slice of all values for the map.
func Must ¶
func Must[T any](t T) T
Must panics if given value is equal to the zero value of the type.
func MustBool ¶ added in v1.35.0
MustBool returns the bool representation of the given value and panics if it cannot.
func MustDuration ¶ added in v1.35.0
MustDuration returns the time.Duration representation of the given value and panics if it cannot.
func MustE ¶
MustE panics if the given func returns an error for the value returned is equal to the zero value of the type.
func MustInt ¶ added in v1.35.0
MustInt returns the int representation of the given value and panics if it cannot.
func MustMapAny ¶ added in v1.38.0
MustMapAny returns the map[string]any of the given value and panics if it cannot.
func MustMapString ¶ added in v1.38.0
MustMapString returns the map[string]string of the given value and panics if it cannot.
func MustString ¶ added in v1.35.0
MustString returns the string representation of the given value and panics if it cannot.
func MustTime ¶ added in v1.50.0
MustTime returns the time.Time representation of the given value and panics if it cannot.
func OptionApply ¶
OptionApply applies all functional options to type t and returns the error if any fail to apply.
func RandomExcluding ¶ added in v1.46.0
func RandomExcluding[T comparable](fn func() T, exclude map[T]struct{}) T
RandomExcluding generates a random value that is not in the excluded set.
Note: Depending on the content of the excluded set, this function may be extremely inefficient.
func RandomNumber ¶ added in v1.44.0
func RandomNumber[T constraints.Integer | constraints.Float](r *Random) T
RandomNumber returns a random number between primitive value min & max.
func RandomNumberRange ¶ added in v1.44.0
func RandomNumberRange[T constraints.Integer | constraints.Float](r *Random, min, max T) T
RandomNumberRange returns a random number between min (inclusive) and max (exclusive).
func RandomRegex ¶ added in v1.44.0
RandomRegex returns a random string that matches a regular expression.
func RandomSelection ¶ added in v1.44.0
RandomSelection returns a random item from the provided list of items.
func RandomString ¶ added in v1.44.0
RandomString returns a random string between min length (inclusive) and max length (exclusive).
func ReturnGlobal ¶ added in v1.60.0
func ReturnGlobal(random *Random)
ReturnGlobal returns the global Random instance and unlocks it.
func SafeDereference ¶ added in v1.54.0
func SafeDereference[T any](t *T) T
SafeDereference dereference the given pointer and return the zero value if the pointer is nil.
func SliceFilter ¶
SliceFilter will return a new slice containing only items from the given input that match the predicate function.
func SliceFilterRange ¶
SliceFilterRange will return a new slice containing only items from the given input ranger that match the predicate function.
func SliceFlatten ¶
func SliceFlatten[T any](input ...[]T) []T
SliceFlatten will flatten a slice of slices into a single slice.
func SliceMap ¶ added in v1.24.0
SliceMap returns a slice with the results from the given 'map' function.
func SliceSet ¶ added in v1.39.0
func SliceSet[T comparable](input []T) map[T]struct{}
SliceSet returns a set from the given slice.
func SliceToMap ¶
func SliceToMap[K comparable, V any](input []V, key func(v V) K) map[K]V
SliceToMap returns a map from the given slice and key function.
func SliceTypeAssert ¶ added in v1.7.0
SliceTypeAssert takes a slice of one type and asserts individual items to the other.
func ToBool ¶ added in v1.36.0
ToBool returns the bool representation of the given value and errors if it cannot.
func ToDuration ¶ added in v1.36.0
ToDuration returns the time.Duration representation of the given value and errors if it cannot.
func ToInt ¶ added in v1.36.0
ToInt returns the int representation of the given value and errors if it cannot.
func ToMapAny ¶ added in v1.38.0
ToMapAny returns the map[string]any representation of the given value and errors if it cannot.
func ToMapString ¶ added in v1.38.0
ToMapString returns the map[string]any representation of the given value and errors if it cannot.
func ToString ¶ added in v1.36.0
ToString returns the string representation of the given value and errors if it cannot.
func ToTime ¶ added in v1.50.0
ToTime returns the time.Time representation of the given value and errors if it cannot.
func URLPort ¶
URLPort returns a port number for the given URL.
If a port was not defined during URL creation, an attempt is made to derive it from the scheme.
func ZeroPad ¶ added in v1.49.0
func ZeroPad[T constraints.Integer](width T, v T) string
ZeroPad returns the given integer as a zero-padded string.
Types ¶
type Bitmask ¶
type Bitmask uint8
Bitmask is a `uint8` with helper methods for bitwise operations.
const ( // ErrorNamespaceDefault is the default namespace for errors generated by this package. ErrorNamespaceDefault = "stdlibx-go" // ErrorFlagUnknown is set to represent unknown/unregistered errors. ErrorFlagUnknown Bitmask = 1 << iota // ErrorFlagRetryable is set to represent errors that can be retried. ErrorFlagRetryable // ErrorFlagTimeout is set to represent errors indicating a timeout occurred. ErrorFlagTimeout )
func ParseBitmask ¶
ParseBitmask creates a new Bitmask from a binary string.
func (Bitmask) MarshalText ¶
MarshalText implements the text marshaller method.
type Causer ¶
type Causer interface {
Cause() error
}
Causer defines types that return the underlying cause of an error.
type CloserFn ¶ added in v1.52.0
type CloserFn func() error
CloserFn is a function that can be used to close resources.
type CloserGroup ¶ added in v1.51.0
CloserGroup is a collection of io.Closer instances that can be closed together.
func CloserJoin ¶ added in v1.51.0
func CloserJoin(closer io.Closer, closers ...io.Closer) *CloserGroup
CloserJoin is a helper function that will append more closers onto an CloserGroup.
If err is not already an ErrorGroup, then it will be turned into one. If any of the errs are ErrorGroup, they will be flattened one level into err. Any nil errors within errs will be ignored. If err is nil, a new *ErrorGroup will be returned containing the given errs.
func NewCloserGroup ¶ added in v1.51.0
func NewCloserGroup(closers ...io.Closer) *CloserGroup
NewCloserGroup creates a new *CloserGroup with sane defaults.
func (*CloserGroup) Append ¶ added in v1.51.0
func (g *CloserGroup) Append(closers ...io.Closer)
Append adds the given closers to the group.
func (*CloserGroup) Close ¶ added in v1.51.0
func (g *CloserGroup) Close() error
Close closes all closers in the group.
type ContextKey ¶ added in v1.10.0
type ContextKey[T any] struct { // contains filtered or unexported fields }
ContextKey is a generic key type associated with a specific value type. This should be used with non-exported Go types to avoid potential key collisions within the context object.
func NewContextKey ¶ added in v1.10.0
func NewContextKey[T any](name string, def T) ContextKey[T]
NewContextKey creates a new context key for a generic type.
func (ContextKey[T]) String ¶ added in v1.10.0
func (k ContextKey[T]) String() string
String returns the name of the key.
func (ContextKey[T]) Value ¶ added in v1.10.0
func (k ContextKey[T]) Value(ctx context.Context) T
Value returns the value in the context associated with this key. If the value is not present, it returns the default value.
func (ContextKey[T]) ValueOk ¶ added in v1.10.0
func (k ContextKey[T]) ValueOk(ctx context.Context) (T, bool)
ValueOk returns the value in the context associated with this key and also reports whether it was present. If the value is not present, it returns the default value.
func (ContextKey[T]) WithValue ¶ added in v1.10.0
func (k ContextKey[T]) WithValue(parent context.Context, value T) context.Context
WithValue returns a copy of parent in which the value associated with key is value.
It is a type-safe equivalent of context.WithValue.
type DataType ¶ added in v1.53.0
type DataType string
DataType is a primitive data type which can be used across system implementations.
ENUM( null, bool, int8, int16, int32, int64, int128, uint8, uint16, uint32, uint64, uint128, float32, float64, bytes, utf8, date, timestamp, timestamp_s, timestamp_ms, list ).
const ( // DataTypeNull is a DataType of type null. DataTypeNull DataType = "null" // DataTypeBool is a DataType of type bool. DataTypeBool DataType = "bool" // DataTypeInt8 is a DataType of type int8. DataTypeInt8 DataType = "int8" // DataTypeInt16 is a DataType of type int16. DataTypeInt16 DataType = "int16" // DataTypeInt32 is a DataType of type int32. DataTypeInt32 DataType = "int32" // DataTypeInt64 is a DataType of type int64. DataTypeInt64 DataType = "int64" // DataTypeInt128 is a DataType of type int128. DataTypeInt128 DataType = "int128" // DataTypeUint8 is a DataType of type uint8. DataTypeUint8 DataType = "uint8" // DataTypeUint16 is a DataType of type uint16. DataTypeUint16 DataType = "uint16" // DataTypeUint32 is a DataType of type uint32. DataTypeUint32 DataType = "uint32" // DataTypeUint64 is a DataType of type uint64. DataTypeUint64 DataType = "uint64" // DataTypeUint128 is a DataType of type uint128. DataTypeUint128 DataType = "uint128" // DataTypeFloat32 is a DataType of type float32. DataTypeFloat32 DataType = "float32" // DataTypeFloat64 is a DataType of type float64. DataTypeFloat64 DataType = "float64" // DataTypeBytes is a DataType of type bytes. DataTypeBytes DataType = "bytes" // DataTypeUtf8 is a DataType of type utf8. DataTypeUtf8 DataType = "utf8" // DataTypeDate is a DataType of type date. DataTypeDate DataType = "date" // DataTypeTimestamp is a DataType of type timestamp. DataTypeTimestamp DataType = "timestamp" // DataTypeTimestampS is a DataType of type timestamp_s. DataTypeTimestampS DataType = "timestamp_s" // DataTypeTimestampMs is a DataType of type timestamp_ms. DataTypeTimestampMs DataType = "timestamp_ms" // DataTypeList is a DataType of type list. DataTypeList DataType = "list" )
func ParseDataType ¶ added in v1.53.0
ParseDataType attempts to convert a string to a DataType.
func ReflectTypeToDataType ¶ added in v1.55.0
func (DataType) IsValid ¶ added in v1.53.0
IsValid provides a quick way to determine if the typed value is part of the allowed enumerated values
func (DataType) MarshalText ¶ added in v1.53.0
MarshalText implements the text marshaller method.
func (*DataType) UnmarshalText ¶ added in v1.53.0
UnmarshalText implements the text unmarshaller method.
type DebugExtras ¶
type DebugExtras struct {
// StackTrace of the error.
StackTrace string `json:"stack_trace,omitempty"`
}
DebugExtras contains helpful information for debugging the error.
func (DebugExtras) IsZero ¶
func (e DebugExtras) IsZero() bool
IsZero returns true if the Extras object is the zero/empty struct value.
type Error ¶
type Error struct {
// Code is a machine-readable representation for the error.
Code string `json:"code"`
// Extras is an optional struct to store execution context
// that is helpful for understanding the error.
Extras ErrorExtras `json:"extras,omitempty"`
// Flags is a bitmask that contains additional classification/context
// for the error, e.g. indicating if the error can be retried.
Flags Bitmask `json:"flags,omitempty"`
// Message is a human-readable representation for the error.
Message string `json:"message"`
// Namespace is a machine-readable representation for a bucketing/grouping
// concept of errors. This is commonly used to indicate the package/repository/service
// an error originated from.
Namespace string `json:"namespace"`
// Wrapped is a wrapped error if this was created from another via `Wrap`. This
// is hidden from human consumers and only visible to machine/operators.
Wrapped error `json:"-"`
}
Error defines a standard application error primitive.
TODO(ahawker) Add Format interface (for pretty strings) TODO(ahawker) Namespace field? Embed in the code?
func (Error) AsGroup ¶
func (e Error) AsGroup() *ErrorGroup
AsGroup returns a *ErrorGroup containing this error and all wrapped errors it contains.
func (Error) Copy ¶
Copy returns a full copy of this Error, including copies of all wrapped errors within.
func (Error) Format ¶
Format returns a complex string representation of the Error for the given verbs.
Interface: fmt.Formatter.
func (Error) IsRetryable ¶
IsRetryable returns true if the error indicates the failed operation is safe to retry.
func (Error) IsTransient ¶
IsTransient returns true if the error indicates the operation failure is transient and a result might be different if tried at another time.
func (Error) WithDebugInfo ¶
func (e Error) WithDebugInfo(extras DebugExtras) Error
WithDebugInfo returns a new copy of the Error with the given debug info added.
func (Error) WithHelp ¶
func (e Error) WithHelp(extras HelpExtras) Error
WithHelp returns a new copy of the Error with the given help info added.
func (Error) WithRetry ¶
func (e Error) WithRetry(extras RetryExtras) Error
WithRetry returns a new copy of the Error with the given retry info added.
func (Error) WithTag ¶ added in v1.31.0
WithTag returns a new copy of the Error with the given tags added.
type ErrorExtras ¶
type ErrorExtras struct {
// Debug information captured from the error.
Debug DebugExtras `json:"debug,omitempty"`
// Help information to inform operators about the error.
Help HelpExtras `json:"help,omitempty"`
// Retry information regarding the failed operation.
Retry RetryExtras `json:"retry,omitempty"`
// Tags are additional labels that can be used to categorize errors.
Tags []string `json:"tags,omitempty"`
}
ErrorExtras contains common additional info attached to errors.
func (ErrorExtras) IsZero ¶
func (e ErrorExtras) IsZero() bool
IsZero returns true if the ErrorExtras object is the zero/empty struct value.
func (ErrorExtras) WithDebugExtras ¶
func (e ErrorExtras) WithDebugExtras(extras DebugExtras) ErrorExtras
WithDebugExtras returns a new copy of the ErrorExtras with the given debug info set.
func (ErrorExtras) WithHelpExtras ¶
func (e ErrorExtras) WithHelpExtras(extras HelpExtras) ErrorExtras
WithHelpExtras returns a new copy of the ErrorExtras with the given help info set.
func (ErrorExtras) WithRetryExtras ¶
func (e ErrorExtras) WithRetryExtras(extras RetryExtras) ErrorExtras
WithRetryExtras returns a new copy of the ErrorExtras with the given retry info set.
func (ErrorExtras) WithTag ¶ added in v1.31.0
func (e ErrorExtras) WithTag(tags ...string) ErrorExtras
WithTag returns a new copy of the ErrorExtras with the given tags set.
type ErrorGroup ¶
type ErrorGroup struct {
// Errors in the group.
Errors []Error `json:"errors"`
// Formatter to convert error group to string representation.
Formatter ErrorGroupFormatter `json:"-"`
}
ErrorGroup stores multiple Error instances.
TODO(ahawker) Flatten JSON output to a single error when group only has one.
func ErrorJoin ¶ added in v1.7.0
func ErrorJoin(err error, errs ...error) *ErrorGroup
ErrorJoin is a helper function that will append more errors onto an ErrorGroup.
If err is not already an ErrorGroup, then it will be turned into one. If any of the errs are ErrorGroup, they will be flattened one level into err. Any nil errors within errs will be ignored. If err is nil, a new *ErrorGroup will be returned containing the given errs.
func NewErrorGroup ¶ added in v1.12.0
func NewErrorGroup(errs ...error) *ErrorGroup
NewErrorGroup creates a new *ErrorGroup with sane defaults.
func NewTranslatedErrorGroup ¶ added in v1.22.0
func NewTranslatedErrorGroup(translate ErrorTranslate, errs ...error) *ErrorGroup
NewTranslatedErrorGroup creates a new *ErrorGroup with sane defaults and translated errors.
func (*ErrorGroup) Append ¶
func (g *ErrorGroup) Append(errs ...error)
Append adds a new error to the group.
If the given error is not an Error instance, it will be wrapped with ErrUndefined.
func (*ErrorGroup) Empty ¶
func (g *ErrorGroup) Empty() bool
Empty will return true if the group is empty.
func (*ErrorGroup) Error ¶
func (g *ErrorGroup) Error() string
Error string value of the ErrorGroup struct.
Interface: error.
func (*ErrorGroup) ErrorOrNil ¶
func (g *ErrorGroup) ErrorOrNil() error
ErrorOrNil returns an error interface if this Error represents a list of errors, or returns nil if the list of errors is empty. This function is useful at the end of accumulation to make sure that the value returned represents the existence of errors.
func (*ErrorGroup) GroupOrNil ¶
func (g *ErrorGroup) GroupOrNil() *ErrorGroup
GroupOrNil returns the ErrorGroup interface if this group represents contains one or more errors. If it's empty, nil is returned.
func (*ErrorGroup) Len ¶
func (g *ErrorGroup) Len() int
Len returns the number of errors in the group.
Interface: sort.Interface.
func (*ErrorGroup) Less ¶
func (g *ErrorGroup) Less(i, j int) bool
Less determines order for sorting a group.
Interface: sort.Interface.
func (*ErrorGroup) Slice ¶
func (g *ErrorGroup) Slice() []Error
Slice returns a slice of all errors in the group.
func (*ErrorGroup) Swap ¶
func (g *ErrorGroup) Swap(i, j int)
Swap moves errors in the group during sorting.
Interface: sort.Interface.
func (*ErrorGroup) Translate ¶ added in v1.21.0
func (g *ErrorGroup) Translate(translate ErrorTranslate)
Translate performs an in-place translation of errors in the group for swapping context.
func (*ErrorGroup) Unwrap ¶
func (g *ErrorGroup) Unwrap() error
Unwrap returns the next error in the group or nil if there are no more errors.
Interface: errors.Unwrap, HasUnwrap.
type ErrorGroupFormatter ¶
ErrorGroupFormatter is a function callback that is called by ErrorGroup to turn the list of errors into a string.
type ErrorTranslate ¶
ErrorTranslate defines function that can translate errors between two different contexts.
This is commonly used to convert between domain and adapter error types.
type FakeConstraintsNumeric ¶ added in v1.44.0
type FakeConstraintsNumeric[T constraints.Integer | constraints.Float] struct { // Cardinality is the number of distinct values. Cardinality uint64 // Dataset is a set of values to choose from. Dataset []T // Min is the minimum value. Min T // Max is the maximum value. Max T }
type FakeConstraintsTextual ¶ added in v1.44.0
type FakeNumber ¶ added in v1.44.0
type FakeNumber[T constraints.Integer | constraints.Float] struct { // Strategy to use for selecting fake values. Strategy FakeStrategy // State holds necessary persistent values for some strategies. State *FakeState[T] // Cardinality is the number of distinct values relative to the total number of generations. Cardinality uint64 // Possible is a fixed set of values to choose from. Possible []T // Min is the minimum value. Min T // Max is the maximum value. Max T // RandomFn is a function that generates a random value without limitations. RandomFn func(ctx context.Context, n *FakeNumber[T]) T // RangeFn is a function that generates a random value within the bounds. RangeFn func(ctx context.Context, n *FakeNumber[T]) T // SelectFn is a function that generates a random value from a set of values. SelectFn func(ctx context.Context, n *FakeNumber[T]) T // StateFn is a function that generates a value based on some state/previous value. StateFn func(ctx context.Context, n *FakeNumber[T]) }
FakeNumber represents a fake number generator.
func (*FakeNumber[T]) Generate ¶ added in v1.44.0
func (n *FakeNumber[T]) Generate(ctx context.Context) T
Generate generates a fake number based on the configured options.
type FakeRequest ¶ added in v1.44.0
type FakeState ¶ added in v1.42.0
type FakeState[T any] struct { // Generation is the numeric value of the previous generation (incrementing). Generation uint64 // Init is the initial stored value from the first generation. Init T // Curr is the stored value from the previous generation. Curr T }
FakeState holds persistent values for some strategies.
type FakeStrategy ¶ added in v1.42.0
type FakeStrategy string
FakeStrategy represents a strategy for choosing a fake value.
unspecified: No strategy specified. random: Randomly generate a value with no bounds or limitations. random_range: Randomly select a value within the bounds. random_select: Randomly select a value from loaded set of values. random_pattern: Randomly select a value from a regex pattern. distribution_normal: Select a value from a normal distribution. distribution_uniform: Select a value from a uniform distribution. stateful: Select a value based on some state/previous value.
ENUM(unspecified, random, random_range, random_pattern, random_select, distribution_normal, distribution_uniform, stateful).
const ( // FakeStrategyUnspecified is a FakeStrategy of type unspecified. FakeStrategyUnspecified FakeStrategy = "unspecified" // FakeStrategyRandom is a FakeStrategy of type random. FakeStrategyRandom FakeStrategy = "random" // FakeStrategyRandomRange is a FakeStrategy of type random_range. FakeStrategyRandomRange FakeStrategy = "random_range" // FakeStrategyRandomPattern is a FakeStrategy of type random_pattern. FakeStrategyRandomPattern FakeStrategy = "random_pattern" // FakeStrategyRandomSelect is a FakeStrategy of type random_select. FakeStrategyRandomSelect FakeStrategy = "random_select" // FakeStrategyDistributionNormal is a FakeStrategy of type distribution_normal. FakeStrategyDistributionNormal FakeStrategy = "distribution_normal" // FakeStrategyDistributionUniform is a FakeStrategy of type distribution_uniform. FakeStrategyDistributionUniform FakeStrategy = "distribution_uniform" // FakeStrategyStateful is a FakeStrategy of type stateful. FakeStrategyStateful FakeStrategy = "stateful" )
func ParseFakeStrategy ¶ added in v1.42.0
func ParseFakeStrategy(name string) (FakeStrategy, error)
ParseFakeStrategy attempts to convert a string to a FakeStrategy.
func (FakeStrategy) IsValid ¶ added in v1.42.0
func (x FakeStrategy) IsValid() bool
IsValid provides a quick way to determine if the typed value is part of the allowed enumerated values
func (FakeStrategy) MarshalText ¶ added in v1.42.0
func (x FakeStrategy) MarshalText() ([]byte, error)
MarshalText implements the text marshaller method.
func (FakeStrategy) String ¶ added in v1.42.0
func (x FakeStrategy) String() string
String implements the Stringer interface.
func (*FakeStrategy) UnmarshalText ¶ added in v1.42.0
func (x *FakeStrategy) UnmarshalText(text []byte) error
UnmarshalText implements the text unmarshaller method.
type FakeText ¶ added in v1.44.0
type FakeText[T ~string] struct { // Strategy to use for selecting fake values. Strategy FakeStrategy // State holds necessary persistent values for some strategies. State *FakeState[T] // Cardinality is the number of distinct values relative to the total number of generations. Cardinality uint64 // Possible is a fixed set of values to choose from. Possible []T // Regex is a regular expression that the value must match. Regex *regexp.Regexp // MinLength is the minimum text length. MinLength uint64 // MaxLength is the maximum text value. MaxLength uint64 // RandomFn is a function that generates a random value without limitations. RandomFn func(ctx context.Context, t *FakeText[T]) T // RangeFn is a function that generates a random value within the bounds. RangeFn func(ctx context.Context, t *FakeText[T]) T // PatternFn is a function that generates a random value that matches a regular expression pattern. PatternFn func(ctx context.Context, t *FakeText[T]) T // SelectFn is a function that generates a random value from a set of values. SelectFn func(ctx context.Context, t *FakeText[T]) T // StateFn is a function that generates a value based on some state/previous value. StateFn func(ctx context.Context, t *FakeText[T]) }
type HasUnwrap ¶
type HasUnwrap interface {
Unwrap() error
}
HasUnwrap defines types necessary for stdlib `errors.Unwrap` support.
type HelpExtras ¶
type HelpExtras struct {
// Links to help documentation regarding the error.
Links []Link `json:"links,omitempty"`
}
HelpExtras contains helpful hyperlinks for the error.
func (HelpExtras) IsZero ¶
func (e HelpExtras) IsZero() bool
IsZero returns true if the Extras object is the zero/empty struct value.
type KeyedMapper ¶ added in v1.24.0
type KeyedMapper[K comparable, VIn any, VOut any] func(k K, v VIn) VOut
KeyedMapper describes a 'map' function for a given key/value input.
type KeyedPredicate ¶
type KeyedPredicate[K comparable, V any] func(k K, v V) bool
KeyedPredicate describes functions which return true/false based on a given key/value input.
type KeyedRanger ¶
type KeyedRanger[K comparable, V any] interface { // Range calls the given function for all items available for iteration. // // If Range returns `false`, iteration will stop. Range(predicate KeyedPredicate[K, V]) }
KeyedRanger describes types that export a `Range` method for iteration over key/value collections.
type Memoize ¶
type Memoize[T any] struct { // Fn is called once and its result/error is cached. Fn func() (T, error) // contains filtered or unexported fields }
Memoize is a simple struct that wraps a `sync.Once` to provide thread safe memoized results for costly computation.
type Option ¶
Option defines functional options for type t.
func WithTaskCancel ¶ added in v1.56.0
func WithTaskCancel(fn TaskCancelFn) Option[*TaskConfig]
WithTaskCancel sets the cancel function for the task.
func WithTaskTimeout ¶ added in v1.56.0
func WithTaskTimeout(timeout time.Duration) Option[*TaskConfig]
WithTaskTimeout sets the timeout for the task.
type Optional ¶ added in v1.34.0
type Optional[T any] struct { // contains filtered or unexported fields }
Optional wraps a value of type `T` tracks a default value and whether it changed.
func Default ¶ added in v1.34.0
Default creates an Optional with an empty value and distinct default value.
type Random ¶ added in v1.60.0
Random represents a random number generator with its source and seed.
Callers are free to create their own and pass them into functions or use the 'Get' and 'Return' functions to borrow the global one.
type Ranger ¶
type Ranger[T any] interface { // Range calls the given function for all items available for iteration. // // If Range returns `false`, iteration will stop. Range(predicate Predicate[T]) }
Ranger describes types that export a `Range` method for iteration over single item collections.
type RetryExtras ¶
type RetryExtras struct {
// Delay duration abide by before retrying the failed operation.
Delay time.Duration
}
RetryExtras contains helpful information for dictating how/why retries can/should happen.
func (RetryExtras) IsZero ¶
func (e RetryExtras) IsZero() bool
IsZero returns true if the Extras object is the zero/empty struct value.
type TaskCancelFn ¶ added in v1.56.0
TaskCancelFn is a function that represents a task cancellation function.
type TaskConfig ¶ added in v1.56.0
type TaskConfig struct {
// Timeout is the max duration for the task to run before cancellation.
Timeout time.Duration
// Cancel is the function to call when the task is cancelled.
Cancel TaskCancelFn
// CancelTimeout is the max duration for the 'TaskCancelFn' to run.
CancelTimeout time.Duration
}
TaskConfig for a task execution.
type Valid ¶ added in v1.13.0
type Valid[T any] struct { // Value of type T which has been validated. Value T }
Valid is a struct that wraps an arbitrary value to indicate that it is valid and has passed all checks.