toolbox: Index | Files | Directories

package toolbox

import ""

Package toolbox - useful set of utilities/abstractions developed as part of datastore connectivity and testing (viant/dsc, viant/dsunit).


Package Files

batch_limiter.go byte_buffer_pool.go collections.go collections_async.go context.go converter.go decoder.go doc.go dumper.go encoder.go error.go file_logger.go fileset_info.go function_util.go iterator.go json.go log_message.go macro.go mime_type.go os_helper.go predicate.go predicates.go ranger.go service_router.go stack_helper.go struct_helper.go text.go time_format.go time_helper.go tokenizer.go types.go uri.go uri_helper.go value_provider.go waitgroup_helper.go writer_at.go yaml.go


const (
    //JSONMimeType JSON  mime type constant
    JSONMimeType = "text/json"
    //CSVMimeType csv  mime type constant
    CSVMimeType = "text/csv"
    //TSVMimeType tab separated mime type constant
    TSVMimeType = "text/tsv"
    //TextMimeType mime type constant
    TextMimeType = "text/sql"
const (
    //MethodGet HTTP GET meothd
    MethodGet     = "GET"
    MethodHead    = "HEAD"
    MethodPost    = "POST"
    MethodPut     = "PUT"
    MethodPatch   = "PATCH" // RFC 5789
    MethodDelete  = "DELETE"
    MethodOptions = "OPTIONS"
    MethodTrace   = "TRACE"
const (
    CaseUpper = iota
const (
    Now       = "now"
    Tomorrow  = "tomorrow"
    Yesterday = "yesterday"

    DurationWeek            = "week"
    DurationDay             = "day"
    DurationHour            = "hour"
    DurationMinute          = "minute"
    DurationMinuteAbbr      = "min"
    DurationSecond          = "second"
    DurationSecondAbbr      = "sec"
    DurationMillisecond     = "millisecond"
    DurationMillisecondAbbr = "ms"
    DurationMicrosecond     = "microsecond"
    DurationMicrosecondAbbr = "us"
    DurationNanosecond      = "nanosecond"
    DurationNanosecondAbbr  = "ns"


var CopyStringValueProvider = func(source string) string {
    return source

CopyStringValueProvider is a function that returns passed in string This provider can be used to make map from slice like map[string]some type

var DateFormatKeyword = "dateFormat"

DateFormatKeyword constant 'dateFormat' key

var DateLayoutKeyword = "dateLayout"

DateLayoutKeyword constant 'dateLayout' key

var DefaultConverter = NewConverter("", "name")

DefaultConverter represents a default data structure converter

var DefaultDateLayout = "2006-01-02 15:04:05.000"

DefaultDateLayout is set to 2006-01-02 15:04:05.000

var DefaultDecoderFactory = NewJSONDecoderFactory()

DefaultDecoderFactory - NewJSONDecoderFactory

var DefaultEncoderFactory = NewJSONEncoderFactory()

DefaultEncoderFactory - NewJSONEncoderFactory

var FileExtensionMimeType = map[string]string{
    "json": JSONMimeType,
    "csv":  CSVMimeType,
    "tsv":  TSVMimeType,
    "sql":  TextMimeType,
    "html": "text/html",
    "js":   "text/javascript",
    "jpg":  "image/jpeg",
    "png":  "image/png",

FileExtensionMimeType json, csv, tsc, sql mime types.

var FileSchema = "file://"

FileSchema file://

var TrueProvider = func(input interface{}) bool {
    return true

TrueProvider represents a true provider

var TrueValueProvider = func(ignore interface{}) bool {
    return true

TrueValueProvider is a function that returns true, it takes one parameters which ignores, This provider can be used to make map from slice like map[some type]bool

var YamlDefaultDecoderFactory = NewFlexYamlDecoderFactory()

YamlDefaultDecoderFactory - NewYamlDecoderFactory

var YamlDefaultEncoderFactory = NewYamlEncoderFactory()

YamlDefaultEncoderFactory - NewYamlEncoderFactory

func AsBoolean Uses

func AsBoolean(value interface{}) bool

AsBoolean converts an input to bool.

func AsCompatibleFunctionParameters Uses

func AsCompatibleFunctionParameters(function interface{}, parameters []interface{}) ([]interface{}, error)

AsCompatibleFunctionParameters takes incompatible function parameters and converts then into provided function signature compatible

func AsFloat Uses

func AsFloat(value interface{}) float64

AsFloat converts an input to float.

func AsFunctionParameters Uses

func AsFunctionParameters(function interface{}, parameters []interface{}, parametersKV map[string]interface{}) ([]interface{}, error)

AsFunctionParameters takes incompatible function parameters and converts then into provided function signature compatible

func AsIndentJSONText Uses

func AsIndentJSONText(source interface{}) (string, error)

AsIndentJSONText converts data structure int text JSON

func AsInt Uses

func AsInt(value interface{}) int

AsInt converts an input to int.

func AsJSONText Uses

func AsJSONText(source interface{}) (string, error)

AsJSONText converts data structure int text JSON

func AsMap Uses

func AsMap(source interface{}) map[string]interface{}

AsMap converts underlying map as map[string]interface{}

func AsSlice Uses

func AsSlice(sourceSlice interface{}) []interface{}

AsSlice converts underlying slice or Ranger as []interface{}

func AsString Uses

func AsString(input interface{}) string

AsString converts an input to string.

func AsTime Uses

func AsTime(value interface{}, dateLayout string) *time.Time

AsTime converts an input to time, it takes time input, dateLaout as parameters.

func AsYamlText Uses

func AsYamlText(source interface{}) (string, error)

AsYamlText converts data structure int text YAML

func AssertKind Uses

func AssertKind(input interface{}, kind reflect.Kind, name string)

AssertKind checks if input is of the passed in kind, if not it panic with message including name

func AssertPointerKind Uses

func AssertPointerKind(input interface{}, kind reflect.Kind, name string)

AssertPointerKind checks if input is a pointer of the passed in kind, if not it panic with message including name

func AssertTypeKind Uses

func AssertTypeKind(dataType reflect.Type, kind reflect.Kind, name string)

AssertTypeKind checks if dataType is of the passed in kind, if not it panic with message including name

func BuildFunctionParameters Uses

func BuildFunctionParameters(function interface{}, parameters []string, parameterValues map[string]interface{}) ([]interface{}, error)

BuildFunctionParameters builds function parameters provided in the parameterValues. Parameters value will be converted if needed to expected by the function signature type. It returns function parameters , or error

func BuildTagMapping Uses

func BuildTagMapping(structTemplatePointer interface{}, mappedKeyTag string, resultExclusionTag string, inheritKeyFromField bool, convertKeyToLowerCase bool, tags []string) map[string](map[string]string)

BuildTagMapping builds map keyed by mappedKeyTag tag value, and value is another map of keys where tag name is presents in the tags parameter.

func CallFunction Uses

func CallFunction(function interface{}, parameters ...interface{}) []interface{}

CallFunction calls passed in function with provided parameters,it returns a function result.

func CallerDirectory Uses

func CallerDirectory(callerIndex int) string

CallerDirectory returns directory of caller source code directory

func CallerInfo Uses

func CallerInfo(callerIndex int) (string, string, int)

CallerInfo return filename, function or file line from the stack

func CanConvertToFloat Uses

func CanConvertToFloat(value interface{}) bool

CanConvertToFloat checkis if float conversion is possible.

func CanConvertToInt Uses

func CanConvertToInt(value interface{}) bool

CanConvertToInt returns true if an input can be converted to int value.

func CanConvertToString Uses

func CanConvertToString(input interface{}) bool

CanConvertToString checks if input can be converted to string

func CopyMapEntries Uses

func CopyMapEntries(sourceMap, targetMap interface{})

CopyMapEntries appends map entry from source map to target map

func CopyNonEmptyMapEntries Uses

func CopyNonEmptyMapEntries(input, output interface{}) (err error)

CopyNonEmptyMapEntries removes empty keys from map result

func CopySliceElements Uses

func CopySliceElements(sourceSlice, targetSlicePointer interface{})

CopySliceElements appends elements from source slice into target This function comes handy if you want to copy from generic []interface{} slice to more specific slice like []string, if source slice element are of the same time

func CopyWithBufferPool Uses

func CopyWithBufferPool(source io.Reader, destination io.Writer, pool httputil.BufferPool) (int64, error)

CopyWithBufferPool copies bytes from passed in source to destination with provided pool

func CountPointers Uses

func CountPointers(value interface{}) int

CountPointers count pointers to undelying non pointer type

func CreateDirIfNotExist Uses

func CreateDirIfNotExist(dirs ...string) error

CreateDirIfNotExist creates directory if they do not exist

func DateFormatToLayout Uses

func DateFormatToLayout(dateFormat string) string

DateFormatToLayout converts java date format into go date layout

func DefaultStructMetaFilter Uses

func DefaultStructMetaFilter(ield reflect.StructField) bool

func DeleteEmptyKeys Uses

func DeleteEmptyKeys(input interface{}) map[string]interface{}

DeleteEmptyKeys removes empty keys from map result

func DereferenceType Uses

func DereferenceType(value interface{}) reflect.Type

DereferenceType dereference passed in value

func DereferenceValue Uses

func DereferenceValue(value interface{}) interface{}

DereferenceValue dereference passed in value

func DereferenceValues Uses

func DereferenceValues(source interface{}) interface{}

DereferenceValues replaces pointer to its value within a generic map or slice

func DiscoverCaller Uses

func DiscoverCaller(offset, maxDepth int, ignoreFiles ...string) (string, string, int)

DiscoverCaller returns the first matched caller info

func DiscoverCollectionValuesAndKind Uses

func DiscoverCollectionValuesAndKind(values interface{}) ([]interface{}, reflect.Kind)

DiscoverCollectionValuesAndKind discovers passed in slice item kind, and returns slice of values converted to discovered type. It tries the following kind int, float, bool, string

func DiscoverComponentType Uses

func DiscoverComponentType(input interface{}) reflect.Type

DiscoverComponentType returns type unwrapped from pointer, slice or map

func DiscoverTypeByKind Uses

func DiscoverTypeByKind(input interface{}, expected reflect.Kind) reflect.Type

DiscoverTypeByKind returns unwrapped input type that matches expected kind, or panic if this is not possible

func DiscoverValueAndKind Uses

func DiscoverValueAndKind(input string) (interface{}, reflect.Kind)

DiscoverValueAndKind discovers input kind, it applies checks of the following types: int, float, bool, string

func DiscoverValueByKind Uses

func DiscoverValueByKind(input interface{}, expected reflect.Kind) reflect.Value

DiscoverValueByKind returns unwrapped input that matches expected kind, or panic if this is not possible

func Dump Uses

func Dump(data interface{})

Dump prints passed in data as JSON

func DumpIndent Uses

func DumpIndent(data interface{}, removeEmptyKeys bool) error

DumpIndent prints passed in data as indented JSON

func ElapsedDay Uses

func ElapsedDay(dateTime time.Time) float64

ElapsedDay returns elapsed pct for passed in day (second elapsed that day over 24 hours)

func ElapsedToday Uses

func ElapsedToday(tz string) (float64, error)

ElapsedToday returns elapsed today time percent, it takes optionally timezone

func ExpandFileTemplate Uses

func ExpandFileTemplate(template string) string

ExpandFileTemplate expands

func ExpandParameters Uses

func ExpandParameters(macroEvaluator *MacroEvaluator, parameters map[string]string) error

ExpandParameters expands passed in parameters as strings

func ExpandValue Uses

func ExpandValue(macroEvaluator *MacroEvaluator, value string) (string, error)

ExpandValue expands passed in value, it returns expanded string value or error

func ExtractMimeType Uses

func ExtractMimeType(file string) string

ExtractMimeType extracts mime type by extension

func ExtractURIParameters Uses

func ExtractURIParameters(templateURI, requestURI string) (map[string]string, bool)

ExtractURIParameters parses URIs to extract {<param>} defined in templateURI from requestURI, it returns extracted parameters and flag if requestURI matched templateURI

func FileExists Uses

func FileExists(filename string) bool

FileExists checks if file exists

func Filename Uses

func Filename(filename string) string

Filename reformat file name

func FilterSliceElements Uses

func FilterSliceElements(sourceSlice interface{}, predicate interface{}, targetSlicePointer interface{})

FilterSliceElements copies elements from sourceSlice to targetSlice if predicate function returns true. Predicate function needs to accept source slice element type and return true.

func GetConverter Uses

func GetConverter(target, source interface{}) (func(target, source interface{}) error, bool)

GetConverter returns register converter for supplied target and source type

func GetFuncSignature Uses

func GetFuncSignature(function interface{}) []reflect.Type

GetFuncSignature returns a function signature

func GetFunction Uses

func GetFunction(owner interface{}, name string) (interface{}, error)

GetFunction returns function for provided owner and name, or error

func GetSliceValue Uses

func GetSliceValue(slice interface{}, index int) interface{}

GetSliceValue gets value from passed in index

func GetTimeLayout Uses

func GetTimeLayout(input interface{}) string

GetTimeLayout returns time laout from passed in map, first it check if DateLayoutKeyword is defined is so it returns it, otherwise it check DateFormatKeyword and if exists converts it to dateLayout If neithers keys exists it panics, please use HasTimeLayout to avoid panic

func GroupSliceElements Uses

func GroupSliceElements(sourceSlice, targetMap, keyFunction interface{})

GroupSliceElements reads source slice and transfer all values returned by keyFunction to a slice in target map.

func HasSliceAnyElements Uses

func HasSliceAnyElements(sourceSlice interface{}, elements ...interface{}) (result bool)

HasSliceAnyElements checks if sourceSlice has any of passed in elements. This method iterates through elements till if finds the first match.

func HasTimeLayout Uses

func HasTimeLayout(input interface{}) bool

HasTimeLayout checks if dateLayout can be taken from the passed in setting map

func IgnoreUnexportedFields Uses

func IgnoreUnexportedFields(structField *StructField) bool

Handler ignoring unexported fields

func IndexSlice Uses

func IndexSlice(slice, resultingMap, keyFunction interface{})

IndexSlice reads passed in slice and applies function that takes a slice item as argument to return a key value. passed in resulting map needs to match key type return by a key function, and accept slice item type as argument.

func IndexSliceAsync Uses

func IndexSliceAsync(slice, resultingMap, keyFunction interface{})

IndexSlice reads passed in slice and applies function that takes a slice item as argument to return a key value. passed in resulting map needs to match key type return by a key function, and accept slice item type as argument.

func InitStruct Uses

func InitStruct(source interface{})

InitStruct initialise any struct pointer to empty struct

func Intersect Uses

func Intersect(a, b interface{}, resultPointer interface{}) error

Intersect find elements presents in slice a and b, match is appended to result slice It accept generic slices, All slices should have items of the same type or interface{} type

func IsASCIIText Uses

func IsASCIIText(candidate string) bool

IsASCIIText return true if supplied string does not have binary data

func IsBool Uses

func IsBool(input interface{}) bool

IsBool returns true if input is a boolean

func IsCompleteJSON Uses

func IsCompleteJSON(candidate string) bool

IsCompleteJSON returns true if supplied represent complete JSON

func IsDirectory Uses

func IsDirectory(location string) bool

IsDirectory checks if file is directory

func IsEOFError Uses

func IsEOFError(err error) bool

IsEOFError returns true if io.EOF

func IsFloat Uses

func IsFloat(input interface{}) bool

IsFloat returns true if input is a float

func IsFunc Uses

func IsFunc(input interface{}) bool

IsFunc returns true if input is a funct

func IsInt Uses

func IsInt(input interface{}) bool

IsInt returns true if input is an int

func IsMap Uses

func IsMap(input interface{}) bool

IsMap returns true if input is a map

func IsNewLineDelimitedJSON Uses

func IsNewLineDelimitedJSON(candidate string) bool

IsNewLineDelimitedJSON returns true if supplied content is multi line delimited JSON

func IsNilPointerError Uses

func IsNilPointerError(err error) bool

IsNilPointerError returns true if error is nil pointer

func IsNotFoundError Uses

func IsNotFoundError(err error) bool

IsNotFoundError checks is supplied error is NotFoundError type

func IsNumber Uses

func IsNumber(input interface{}) bool

IsNumber returns true if type is either float or int

func IsPointer Uses

func IsPointer(input interface{}) bool

IsPointer returns true if input is a pointer

func IsPrintText Uses

func IsPrintText(candidate string) bool

IsPrintText return true if all candidate characters are printable (unicode.IsPrintText)

func IsSlice Uses

func IsSlice(input interface{}) bool

IsSlice returns true if input is a map

func IsString Uses

func IsString(input interface{}) bool

IsString returns true if input is a string

func IsStruct Uses

func IsStruct(input interface{}) bool

IsStruct returns true if input is a map

func IsStructuredJSON Uses

func IsStructuredJSON(candidate string) bool

IsStructuredJSON returns true if supplied represent JSON structure (map,array)

func IsTime Uses

func IsTime(input interface{}) bool

IsTime returns true if input is a time

func IsValueOfKind Uses

func IsValueOfKind(input interface{}, kind reflect.Kind) bool

IsValueOfKind returns true if passed in input is of supplied kind.

func IsZero Uses

func IsZero(input interface{}) bool

IsZero returns true if input is a zeroable

func JSONToInterface Uses

func JSONToInterface(source interface{}) (interface{}, error)

JSONToInterface converts JSON source to an interface (either map or slice)

func JSONToMap Uses

func JSONToMap(source interface{}) (map[string]interface{}, error)

JSONToMap converts JSON source into map

func JSONToSlice Uses

func JSONToSlice(source interface{}) ([]interface{}, error)

JSONToSlice converts JSON source into slice

func JoinAsString Uses

func JoinAsString(slice interface{}, separator string) string

JoinAsString joins all items of a slice, with separator, it takes any slice as argument,

func MakeMap Uses

func MakeMap(text string, valueSeparator string, itemSeparator string) map[string]interface{}

MakeMap creates a mapstring]interface{} from string,

func MakeReverseStringMap Uses

func MakeReverseStringMap(text string, valueSepartor string, itemSeparator string) map[string]string

MakeReverseStringMap creates a mapstring]string from string, the values become key, and key values

func MakeStringMap Uses

func MakeStringMap(text string, valueSeparator string, itemSeparator string) map[string]string

MakeStringMap creates a mapstring]string from string,

func MapKeysToSlice Uses

func MapKeysToSlice(sourceMap interface{}, targetSlicePointer interface{}) error

MapKeysToSlice appends all map keys to targetSlice

func MapKeysToStringSlice Uses

func MapKeysToStringSlice(sourceMap interface{}) []string

MapKeysToStringSlice creates a string slice from sourceMap keys, keys do not need to be of a string type.

func NewBytes Uses

func NewBytes(input []byte) []byte

NewBytes copies from input

func NewBytesBufferPool Uses

func NewBytesBufferPool(poolSize, bufferSize int) httputil.BufferPool

NewBytesBufferPool returns new httputil.BufferPool pool.

func NewDuration Uses

func NewDuration(value int, unit string) (time.Duration, error)

NewDuration returns a durationToken for supplied value and time unit, 3, "second"

func NewFieldSettingByKey Uses

func NewFieldSettingByKey(aStruct interface{}, key string) map[string](map[string]string)

NewFieldSettingByKey reads field's tags and returns them indexed by passed in key, fieldName is always part of the resulting map unless filed has "transient" tag.

func NewHttpClient Uses

func NewHttpClient(options ...*HttpOptions) (*http.Client, error)

func NewIllegalTokenError Uses

func NewIllegalTokenError(message string, expected []int, position int, found *Token) error

NewIllegalTokenError create a new illegal token error

func NewLineDelimitedJSON Uses

func NewLineDelimitedJSON(candidate string) ([]interface{}, error)

NewLineDelimitedJSON returns JSON for supplied multi line JSON

func NewNilPointerError Uses

func NewNilPointerError(message string) error

NewNilPointerError creates a new nil pointer error

func NormalizeKVPairs Uses

func NormalizeKVPairs(source interface{}) (interface{}, error)

NormalizeKVPairs converts slice of KV paris into a map, and map[interface{}]interface{} to map[string]interface{}

func OpenFile Uses

func OpenFile(filename string) (*os.File, error)

OpenFile open file converting path to elements and rebuling path safety with path.Join

func Pairs Uses

func Pairs(params ...interface{}) map[string]interface{}

Pairs returns map for pairs.

func ParseTime Uses

func ParseTime(input, layout string) (time.Time, error)

ParseTime parses time, adjusting date layout to length of input

func Process2DSliceInBatches Uses

func Process2DSliceInBatches(slice [][]interface{}, size int, handler func(batchedSlice [][]interface{}))

Process2DSliceInBatches iterates over any 2 dimensional slice, it calls handler with batch.

func ProcessMap Uses

func ProcessMap(source interface{}, handler func(key, value interface{}) bool) error

ProcessMap iterates over any map, it calls handler with every key, value pair unless handler returns false.

func ProcessSlice Uses

func ProcessSlice(slice interface{}, handler func(item interface{}) bool)

ProcessSlice iterates over any slice, it calls handler with each element unless handler returns false,

func ProcessSliceAsync Uses

func ProcessSliceAsync(slice interface{}, handler func(item interface{}) bool)

ProcessSliceAsync iterates over any slice, it calls handler with each element asynchronously

func ProcessSliceWithIndex Uses

func ProcessSliceWithIndex(slice interface{}, handler func(index int, item interface{}) bool)

ProcessSliceWithIndex iterates over any slice, it calls handler with every index and item unless handler returns false

func ProcessSliceWithIndexAsync Uses

func ProcessSliceWithIndexAsync(slice interface{}, handler func(index int, item interface{}) bool)

func ProcessStruct Uses

func ProcessStruct(aStruct interface{}, handler func(fieldType reflect.StructField, field reflect.Value) error) error

ProcessStruct reads passed in struct fields and values to pass it to provided handler

func QueryBoolValue Uses

func QueryBoolValue(u *url.URL, name string, defaultValue bool) bool

QueryBoolValue returns query value for passed in url's name or default value

func QueryIntValue Uses

func QueryIntValue(u *url.URL, name string, defaultValue int) int

QueryIntValue returns query value for passed in url's name or default value

func QueryValue Uses

func QueryValue(u *url.URL, name, defaultValue string) string

QueryValue returns query value for passed in url's name or default value

func ReclassifyNotFoundIfMatched Uses

func ReclassifyNotFoundIfMatched(err error, URL string) error

ReclassifyNotFoundIfMatched reclassify error if not found

func RegisterConverter Uses

func RegisterConverter(target, source reflect.Type, converter func(target, source interface{}) error)

RegisterConverter register custom converter for supplied target, source type

func RemainingToday Uses

func RemainingToday(tz string) (float64, error)

RemainingToday returns remaining today time percent, it takes optionally timezone

func RemoveFileIfExist Uses

func RemoveFileIfExist(filenames ...string) error

RemoveFileIfExist remove file if exists

func ReplaceMapEntries Uses

func ReplaceMapEntries(input, output interface{}, replacement map[string]interface{}, removeEmpty bool) (err error)

CopyNonEmptyMapEntries removes empty keys from map result

func ReplaceMapKeys Uses

func ReplaceMapKeys(input interface{}, replacement map[string]interface{}, removeEmpty bool) map[string]interface{}

DeleteEmptyKeys removes empty keys from map result

func ReverseSlice Uses

func ReverseSlice(source interface{})

ReverseSlice reverse a slice

func RouteToService Uses

func RouteToService(method, url string, request, response interface{}, options ...*HttpOptions) (err error)

RouteToService calls web service url, with passed in json request, and encodes http json response into passed response

func ScanStructMethods Uses

func ScanStructMethods(structOrItsType interface{}, depth int, handler func(method reflect.Method) error) error

ScanStructFunc scan supplied struct methods

func SetSliceValue Uses

func SetSliceValue(slice interface{}, index int, value interface{})

SetSliceValue sets value at slice index

func SetStructMetaFilter Uses

func SetStructMetaFilter(filter StructMetaFilter) error

SetStructMetaFilter sets struct meta filter

func SetUnexportedFieldHandler Uses

func SetUnexportedFieldHandler(handler UnexportedFieldHandler) error

func SliceToMap Uses

func SliceToMap(sourceSlice, targetMap, keyFunction, valueFunction interface{})

SliceToMap reads passed in slice to to apply the key and value function for each item. Result of these calls is placed in the resulting map.

func SliceToMapAsync Uses

func SliceToMapAsync(sourceSlice, targetMap, keyFunction, valueFunction interface{})

SliceToMap reads passed in slice to to apply the key and value function for each item. Result of these calls is placed in the resulting map.

func SliceToMultimap Uses

func SliceToMultimap(sourceSlice, targetMap, keyFunction, valueFunction interface{})

SliceToMultimap reads source slice and transfer all values by valueFunction and returned by keyFunction to a slice in target map. Key and value function result type need to agree with target map type.

func SortStrings Uses

func SortStrings(source []string) []string

SortStrings creates a new copy of passed in slice and sorts it.

func SplitTextStream Uses

func SplitTextStream(reader io.Reader, writerProvider func() io.WriteCloser, elementCount int) error

SplitTextStream divides reader supplied text by number of specified line

func TerminatedSplitN Uses

func TerminatedSplitN(text string, fragmentCount int, terminator string) []string

TerminatedSplitN split supplied text into n fragmentCount, each terminated with supplied terminator

func TimeAt Uses

func TimeAt(offsetExpression string) (*time.Time, error)

TimeAt returns time of now supplied offsetExpression, this function uses TimeDiff

func TimeDiff Uses

func TimeDiff(base time.Time, expression string) (*time.Time, error)

TimeDiff returns time for supplied base time and literal, the supported literal now, yesterday, tomorrow, or the following template:

- [timeValueToken]  durationToken past_or_future_modifier [IN tz]

where time modifier can be any of the following: "onward", "ahead", "after", "later", or "past", "ago", "before", "earlier", "in the future", "in the past") )

func TimestampToString Uses

func TimestampToString(dateFormat string, unixTimestamp, unixNanoTimestamp int64) string

TimestampToString formats timestamp to passed in java style date format

func ToBoolean Uses

func ToBoolean(value interface{}) (bool, error)

ToBoolean converts an input to bool.

func ToCaseFormat Uses

func ToCaseFormat(text string, from, to int) string

ToCaseFormat format text, from, to are const: CaseLower, CaseUpperCamel, CaseLowerCamel, CaseUpperUnderscore, CaseLowerUnderscore,

func ToFloat Uses

func ToFloat(value interface{}) (float64, error)

ToFloat converts an input to float or error

func ToInt Uses

func ToInt(value interface{}) (int, error)

ToInt converts input value to int or error

func ToMap Uses

func ToMap(source interface{}) (map[string]interface{}, error)

ToMap converts underlying map/struct/[]KV as map[string]interface{}

func ToTime Uses

func ToTime(value interface{}, dateLayout string) (*time.Time, error)

ToTime converts value to time, optionally uses layout if value if of string type

func TransformSlice Uses

func TransformSlice(sourceSlice, targetSlicePointer, transformer interface{})

TransformSlice appends transformed elements from source slice into target, transformer take as argument item of source slice and return value of target slice.

func TryDiscoverTypeByKind Uses

func TryDiscoverTypeByKind(input interface{}, expected reflect.Kind) (reflect.Type, error)

TryDiscoverTypeByKind returns unwrapped input type that matches expected kind, or error

func TryDiscoverValueByKind Uses

func TryDiscoverValueByKind(input interface{}, expected reflect.Kind) (reflect.Value, error)

TryDiscoverValueByKind returns unwrapped input that matches expected kind, or panic if this is not possible

func URLBase Uses

func URLBase(URL string) string

URLBase returns base URL

func URLPathJoin Uses

func URLPathJoin(baseURL, path string) string

URLPathJoin joins URL paths

func URLSplit Uses

func URLSplit(URL string) (string, string)

URLSplit returns URL with parent path and resource name

func URLStripPath Uses

func URLStripPath(URL string) string

URLStripPath removes path from URL

func UnwrapValue Uses

func UnwrapValue(value *reflect.Value) interface{}

UnwrapValue returns value

func WaitTimeout Uses

func WaitTimeout(wg *sync.WaitGroup, duration time.Duration) bool

WaitGroup that waits with a timeout Returns true if timeout exceeded and false if there was no timeout

func WriteServiceRoutingResponse Uses

func WriteServiceRoutingResponse(response http.ResponseWriter, request *http.Request, serviceRouting *ServiceRouting, result interface{}) error

WriteServiceRoutingResponse writes service router response

type AnyJSONType Uses

type AnyJSONType string

AnyJSONType represents any JSON type

func (*AnyJSONType) MarshalJSON Uses

func (s *AnyJSONType) MarshalJSON() ([]byte, error)

MarshalJSON implements marshaler interface

func (*AnyJSONType) UnmarshalJSON Uses

func (s *AnyJSONType) UnmarshalJSON(b []byte) error

UnmarshalJSON implements unmarshalerinterface

func (AnyJSONType) Value Uses

func (s AnyJSONType) Value() (interface{}, error)

Value returns string or string slice value

type AtTime Uses

type AtTime struct {
    WeekDay string
    Hour    string
    Minute  string
    TZ      string
    // contains filtered or unexported fields

AtTime represents a time at given schedule

func (*AtTime) Init Uses

func (t *AtTime) Init() error

Init initializes tz

func (*AtTime) Next Uses

func (t *AtTime) Next(base time.Time) time.Time

Next returns next time schedule

type BatchLimiter Uses

type BatchLimiter struct {
    Mutex *sync.RWMutex
    // contains filtered or unexported fields

BatchLimiter represents a batch limiter

func NewBatchLimiter Uses

func NewBatchLimiter(batchSize, total int) *BatchLimiter

NewBatchLimiter creates a new batch limiter with batch size and total number of elements

func (*BatchLimiter) Acquire Uses

func (r *BatchLimiter) Acquire()

Acquire takes token form a channel, or wait if no more elements in a a channel

func (*BatchLimiter) Add Uses

func (r *BatchLimiter) Add(delta int)

Add adds element to wait group

func (*BatchLimiter) Done Uses

func (r *BatchLimiter) Done()

Done flags wait group as done, returns back a token to a channel

func (*BatchLimiter) Wait Uses

func (r *BatchLimiter) Wait()

Wait wait on wait group

type BlockMatcher Uses

type BlockMatcher struct {
    CaseSensitive      bool
    SequenceStart      string
    SequenceTerminator string
    NestedSequences    []string
    IgnoredTerminators []string

func (*BlockMatcher) Match Uses

func (m *BlockMatcher) Match(input string, offset int) (matched int)

type BodyMatcher Uses

type BodyMatcher struct {
    Begin string
    End   string

LiteralMatcher represents a matcher that finds any literals in the input

func (*BodyMatcher) Match Uses

func (m *BodyMatcher) Match(input string, offset int) (matched int)

Match matches a literal in the input, it returns number of character matched.

type ByteWriterAt Uses

type ByteWriterAt struct {
    Buffer []byte
    // contains filtered or unexported fields

ByteWriterAt represents a bytes writer at

func NewByteWriterAt Uses

func NewByteWriterAt() *ByteWriterAt

NewWriterAt returns a new instance of byte writer at

func (*ByteWriterAt) WriteAt Uses

func (w *ByteWriterAt) WriteAt(p []byte, offset int64) (n int, err error)

WriteAt returns number of written bytes or error

type CharactersMatcher Uses

type CharactersMatcher struct {
    Chars string //characters to be matched

CharactersMatcher represents a matcher, that matches any of Chars.

func (CharactersMatcher) Match Uses

func (m CharactersMatcher) Match(input string, offset int) int

Match matches any characters defined in Chars in the input, returns 1 if character has been matched

type ConstValueProvider Uses

type ConstValueProvider struct {
    Value string

ConstValueProvider represnet a const value provider

func (ConstValueProvider) Get Uses

func (p ConstValueProvider) Get(context Context, arguments ...interface{}) (interface{}, error)

Get return provider value

type ContentTypeAccessor Uses

type ContentTypeAccessor interface {
    GetContentType() string

ContentTypeAccessor server side response accessor

type ContentTypeMutator Uses

type ContentTypeMutator interface {
    SetContentType(contentType string)

ContentTypeMutator client side reponse optional interface

type Context Uses

type Context interface {

    //GetRequired returns a value for a target type of error if it does not exist
    GetRequired(targetType interface{}) (interface{}, error)

    //GetOptional  returns a value for a target type
    GetOptional(targetType interface{}) interface{}

    //GetOptional into sets requested context value into target, returns true if value was found
    GetInto(targetType interface{}, target interface{}) bool

    //Put puts target type value to the context, or error if value exists,  is nil or incompatible with target type
    Put(targetType interface{}, value interface{}) error

    //Replace repaces value in the context
    Replace(targetType interface{}, value interface{}) error

    //Remove removes value from the context
    Remove(targetType interface{}) interface{}

    //Contains chekcs if a value of a terget type is in contet
    Contains(targetType interface{}) bool

    //Clone create a shallow copy of a context
    Clone() Context

Context represents type safe map.

func NewContext Uses

func NewContext() Context

NewContext creates a new context

type Converter Uses

type Converter struct {
    DateLayout   string
    MappedKeyTag string

Converter represets data converter, it converts incompatibe data structure, like map and struct, string and time, *string to string, etc.

func NewColumnConverter Uses

func NewColumnConverter(dateLayout string) *Converter

NewColumnConverter create a new converter, that has ability to convert map to struct using column mapping

func NewConverter Uses

func NewConverter(dateLayout, keyTag string) *Converter

NewConverter create a new converter, that has ability to convert map to struct, it uses keytag to identify source and dest of fields/keys

func (*Converter) AssignConverted Uses

func (c *Converter) AssignConverted(target, source interface{}) error

AssignConverted assign to the target source, target needs to be pointer, input has to be convertible or compatible type

type Decoder Uses

type Decoder interface {
    //Decode  reads and decodes objects from an input stream.
    Decode(v interface{}) error

Decoder represents a decoder.

type DecoderFactory Uses

type DecoderFactory interface {
    //Create a decoder for passed in io reader
    Create(reader io.Reader) Decoder

DecoderFactory create an decoder for passed in input stream

func NewDelimiterDecoderFactory Uses

func NewDelimiterDecoderFactory() DecoderFactory

NewDelimiterDecoderFactory returns a new delimitered decoder factory.

func NewFlexYamlDecoderFactory Uses

func NewFlexYamlDecoderFactory() DecoderFactory

NewFlexYamlDecoderFactory create a new yaml decoder factory

func NewJSONDecoderFactory Uses

func NewJSONDecoderFactory() DecoderFactory

NewJSONDecoderFactory create a new JSONDecoderFactory

func NewJSONDecoderFactoryWithOption Uses

func NewJSONDecoderFactoryWithOption(useNumber bool) DecoderFactory

NewJSONDecoderFactoryWithOption create a new JSONDecoderFactory, it takes useNumber decoder parameter

func NewUnMarshalerDecoderFactory Uses

func NewUnMarshalerDecoderFactory() DecoderFactory

NewUnMarshalerDecoderFactory returns a decoder factory

func NewYamlDecoderFactory Uses

func NewYamlDecoderFactory() DecoderFactory

NewYamlDecoderFactory create a new yaml decoder factory

type DelimitedRecord Uses

type DelimitedRecord struct {
    Columns   []string
    Delimiter string
    Record    map[string]interface{}

DelimitedRecord represents a delimited record

func (*DelimitedRecord) IsEmpty Uses

func (r *DelimitedRecord) IsEmpty() bool

IsEmpty returns true if all values are empty or null

type Dictionary Uses

type Dictionary interface {
    //Get returns value for passed in key or error
    Get(key string) (interface{}, error)

    //Exists checks if key exists
    Exists(key string) bool

Dictionary represents simply lookup interface

type Duration Uses

type Duration struct {
    Value int
    Unit  string

Duration represents duration

func (Duration) Duration Uses

func (d Duration) Duration() (time.Duration, error)

Duration return durations

type EOFMatcher Uses

type EOFMatcher struct {

EOFMatcher represents end of input matcher

func (EOFMatcher) Match Uses

func (m EOFMatcher) Match(input string, offset int) int

Match returns 1 if end of input has been reached otherwise 0

type Encoder Uses

type Encoder interface {
    //Encode encodes  an instance to output stream
    Encode(object interface{}) error

Encoder writes an instance to output stream

type EncoderFactory Uses

type EncoderFactory interface {
    //Create creates an encoder for an output stream
    Create(writer io.Writer) Encoder

EncoderFactory create an encoder for an output stream

func NewJSONEncoderFactory Uses

func NewJSONEncoderFactory() EncoderFactory

NewJSONEncoderFactory creates new NewJSONEncoderFactory

func NewMarshalerEncoderFactory Uses

func NewMarshalerEncoderFactory() EncoderFactory

NewMarshalerEncoderFactory create a new encoder factory for marsheler struct

func NewYamlEncoderFactory Uses

func NewYamlEncoderFactory() EncoderFactory

NewYamlEncoderFactory create a new yaml encoder factory

type FieldInfo Uses

type FieldInfo struct {
    Name               string
    TypeName           string
    ComponentType      string
    IsPointerComponent bool
    KeyTypeName        string
    ValueTypeName      string
    TypePackage        string
    IsAnonymous        bool
    IsMap              bool
    IsChannel          bool
    IsSlice            bool
    IsPointer          bool
    Tag                string
    Comment            string
    IsVariant          bool

FieldInfo represents a filed info

func NewFieldInfo Uses

func NewFieldInfo(field *ast.Field) *FieldInfo

NewFieldInfo creates a new field info.

func NewFieldInfoByIndex Uses

func NewFieldInfoByIndex(field *ast.Field, index int) *FieldInfo

NewFieldInfoByIndex creates a new field info.

type FileInfo Uses

type FileInfo struct {
    Imports map[string]string
    // contains filtered or unexported fields

FileInfo represent hold definition about all defined types and its receivers in a file

func NewFileInfo Uses

func NewFileInfo(basePath, packageName, filename string, fileSet *token.FileSet) *FileInfo

NewFileInfo creates a new file info.

func (*FileInfo) HasType Uses

func (f *FileInfo) HasType(name string) bool

HasType returns truc if struct info is defined in a file

func (*FileInfo) Type Uses

func (f *FileInfo) Type(name string) *TypeInfo

Type returns a type info for passed in name

func (*FileInfo) Types Uses

func (f *FileInfo) Types() []*TypeInfo

Types returns all struct info

func (*FileInfo) Visit Uses

func (f *FileInfo) Visit(node ast.Node) ast.Visitor

Visit visits ast node to extract struct details from the passed file

type FileLogger Uses

type FileLogger struct {
    // contains filtered or unexported fields

FileLogger represents a file logger

func NewFileLogger Uses

func NewFileLogger(configs ...FileLoggerConfig) (*FileLogger, error)

NewFileLogger create new file logger

func (*FileLogger) Log Uses

func (l *FileLogger) Log(message *LogMessage) error

Log logs message into stream

func (*FileLogger) NewLogStream Uses

func (l *FileLogger) NewLogStream(path string, config *FileLoggerConfig) (*LogStream, error)

NewLogStream creat a new LogStream for passed om path and file config

func (*FileLogger) Notify Uses

func (l *FileLogger) Notify(siginal os.Signal)

Notify notifies logger

type FileLoggerConfig Uses

type FileLoggerConfig struct {
    LogType            string
    FileTemplate       string
    QueueFlashCount    int
    MaxQueueSize       int
    FlushRequencyInMs  int //type backward-forward compatibility
    FlushFrequencyInMs int
    MaxIddleTimeInSec  int

FileLoggerConfig represents FileLogger

func (*FileLoggerConfig) Validate Uses

func (c *FileLoggerConfig) Validate() error

Validate valides configuration sttings

type FileSetInfo Uses

type FileSetInfo struct {
    // contains filtered or unexported fields

FileSetInfo represents a fileset info storing information about go file with their struct definition

func NewFileSetInfo Uses

func NewFileSetInfo(baseDir string) (*FileSetInfo, error)

NewFileSetInfo creates a new fileset info

func (*FileSetInfo) FileInfo Uses

func (f *FileSetInfo) FileInfo(name string) *FileInfo

FileInfo returns fileinfo for supplied file name

func (*FileSetInfo) FilesInfo Uses

func (f *FileSetInfo) FilesInfo() map[string]*FileInfo

FilesInfo returns all files info.

func (*FileSetInfo) Type Uses

func (f *FileSetInfo) Type(name string) *TypeInfo

Type returns type info for passed in type name.

type FunctionInfo Uses

type FunctionInfo struct {
    Name             string
    ReceiverTypeName string
    ParameterFields  []*FieldInfo
    ResultsFields    []*FieldInfo

FunctionInfo represents a function info

func NewFunctionInfo Uses

func NewFunctionInfo(funcDeclaration *ast.FuncDecl, owner *FileInfo) *FunctionInfo

NewFunctionInfo create a new function

func NewFunctionInfoFromField Uses

func NewFunctionInfoFromField(field *ast.Field, owner *FileInfo) *FunctionInfo

NewFunctionInfoFromField creates a new function info.

type HandlerInvoker Uses

type HandlerInvoker func(serviceRouting *ServiceRouting, request *http.Request, response http.ResponseWriter, parameters map[string]interface{}) error

HandlerInvoker method is responsible of passing required parameters to router handler.

type HttpOptions Uses

type HttpOptions struct {
    Key   string
    Value interface{}

type IdMatcher Uses

type IdMatcher struct{}

LiteralMatcher represents a matcher that finds any literals in the input

func (IdMatcher) Match Uses

func (m IdMatcher) Match(input string, offset int) int

Match matches a literal in the input, it returns number of character matched.

type IllegalTokenError Uses

type IllegalTokenError struct {
    Illegal  *Token
    Message  string
    Expected []int
    Position int

IllegalTokenError represents illegal token error

func (*IllegalTokenError) Error Uses

func (e *IllegalTokenError) Error() string

type IntMatcher Uses

type IntMatcher struct{}

IntMatcher represents a matcher that finds any int in the input

func (IntMatcher) Match Uses

func (m IntMatcher) Match(input string, offset int) int

Match matches a literal in the input, it returns number of character matched.

type Iterator Uses

type Iterator interface {
    //HasNext returns true if iterator has next element.
    HasNext() bool

    //Next sets item pointer with next element.
    Next(itemPointer interface{}) error

Iterator represents generic iterator.

func NewSliceIterator Uses

func NewSliceIterator(slice interface{}) Iterator

NewSliceIterator creates a new slice iterator.

type KeywordMatcher Uses

type KeywordMatcher struct {
    Keyword       string
    CaseSensitive bool

KeywordMatcher represents a keyword matcher

func (KeywordMatcher) Match Uses

func (m KeywordMatcher) Match(input string, offset int) (matched int)

Match matches keyword in the input, it returns number of character matched.

type KeywordsMatcher Uses

type KeywordsMatcher struct {
    Keywords      []string
    CaseSensitive bool

KeywordsMatcher represents a matcher that finds any of specified keywords in the input

func (KeywordsMatcher) Match Uses

func (m KeywordsMatcher) Match(input string, offset int) (matched int)

Match matches any specified keyword, it returns number of character matched.

type LiteralMatcher Uses

type LiteralMatcher struct{}

LiteralMatcher represents a matcher that finds any literals in the input

func (LiteralMatcher) Match Uses

func (m LiteralMatcher) Match(input string, offset int) int

Match matches a literal in the input, it returns number of character matched.

type LogMessage Uses

type LogMessage struct {
    MessageType string
    Message     interface{}

LogMessage represent log message

type LogMessages Uses

type LogMessages struct {
    Messages []LogMessage

LogMessages represents log messages

type LogStream Uses

type LogStream struct {
    Name             string
    Logger           *FileLogger
    Config           *FileLoggerConfig
    RecordCount      int
    File             *os.File
    LastAddQueueTime time.Time
    LastWriteTime    uint64
    Messages         chan string
    Complete         chan bool

LogStream represents individual log stream

func (*LogStream) Close Uses

func (s *LogStream) Close()

Close closes stream.

func (*LogStream) Log Uses

func (s *LogStream) Log(message *LogMessage) error

Log logs message into stream

type MacroEvaluator Uses

type MacroEvaluator struct {
    Prefix, Postfix       string
    ValueProviderRegistry ValueProviderRegistry

MacroEvaluator represents a macro expression evaluator, macros has the following format macro prefix [macro parameter] macro postfix

func NewMacroEvaluator Uses

func NewMacroEvaluator(prefix, postfix string, registry ValueProviderRegistry) *MacroEvaluator

NewMacroEvaluator returns a new macro evaluator

func (*MacroEvaluator) Expand Uses

func (e *MacroEvaluator) Expand(context Context, input string) (interface{}, error)

Expand expands passed in input, it returns expanded value of any type or error

func (*MacroEvaluator) HasMacro Uses

func (e *MacroEvaluator) HasMacro(candidate string) bool

HasMacro checks if candidate has a macro fragment

type MapDictionary Uses

type MapDictionary map[string]interface{}

MapDictionary alias to map of string and interface{}

func (*MapDictionary) Exists Uses

func (d *MapDictionary) Exists(name string) bool

func (*MapDictionary) Get Uses

func (d *MapDictionary) Get(name string) (interface{}, error)

type Marshaler Uses

type Marshaler interface {
    //Marshal converts bytes to attributes of owner struct
    Marshal() (data []byte, err error)

Marshaler represents byte to object converter

type Matcher Uses

type Matcher interface {
    //Match matches input starting from offset, it return number of characters matched
    Match(input string, offset int) (matched int)

Matcher represents a matcher, that matches input from offset position, it returns number of characters matched.

func NewBlockMatcher Uses

func NewBlockMatcher(caseSensitive bool, sequenceStart string, sequenceTerminator string, nestedSequences []string, ignoredTerminators []string) Matcher

Parses SQL Begin End blocks

func NewBodyMatcher Uses

func NewBodyMatcher(begin, end string) Matcher

NewBodyMatcher creates a new body matcher

func NewCharactersMatcher Uses

func NewCharactersMatcher(chars string) Matcher

NewCharactersMatcher creates a new character matcher

func NewCustomIdMatcher Uses

func NewCustomIdMatcher(allowedChars ...string) Matcher

NewCustomIdMatcher creates new custom matcher

func NewIntMatcher Uses

func NewIntMatcher() Matcher

NewIntMatcher returns a new integer matcher

func NewKeywordsMatcher Uses

func NewKeywordsMatcher(caseSensitive bool, keywords ...string) Matcher

NewKeywordsMatcher returns a matcher for supplied keywords

func NewRemainingSequenceMatcher Uses

func NewRemainingSequenceMatcher() Matcher

Creates a matcher that matches all remaining input

func NewSequenceMatcher Uses

func NewSequenceMatcher(terminators ...string) Matcher

NewSequenceMatcher creates a new matcher that finds all sequence until find at least one of the provided terminators

func NewTerminatorMatcher Uses

func NewTerminatorMatcher(terminators ...string) Matcher

NewTerminatorMatcher creates a new matcher that finds any sequence until find at least one of the provided terminators

type NilPointerError Uses

type NilPointerError struct {
    // contains filtered or unexported fields

NilPointerError represents nil pointer error

func (*NilPointerError) Error Uses

func (e *NilPointerError) Error() string

Error returns en error

type NotFoundError Uses

type NotFoundError struct {
    URL string

NotFoundError represents not found error

func (*NotFoundError) Error Uses

func (e *NotFoundError) Error() string

type Predicate Uses

type Predicate interface {
    //Apply checks if predicate is true
    Apply(value interface{}) bool

Predicate represents a generic predicate

func NewBetweenPredicate Uses

func NewBetweenPredicate(from, to interface{}) Predicate

NewBetweenPredicate creates a new BETWEEN predicate, it takes from, and to.

func NewComparablePredicate Uses

func NewComparablePredicate(operator string, leftOperand interface{}) Predicate

NewComparablePredicate create a new comparable predicate for =, !=, >=, <=

func NewInPredicate Uses

func NewInPredicate(values ...interface{}) Predicate

NewInPredicate creates a new IN predicate

func NewLikePredicate Uses

func NewLikePredicate(matching string) Predicate

NewLikePredicate create a new like predicate

func NewNilPredicate Uses

func NewNilPredicate() Predicate

NewNilPredicate returns a new nil predicate

func NewWithinPredicate Uses

func NewWithinPredicate(baseTime time.Time, deltaInSeconds int, dateLayout string) Predicate

NewWithinPredicate returns new NewWithinPredicate predicate, it takes base time, delta in second, and dateLayout

type Ranger Uses

type Ranger interface {
    Range(func(item interface{}) (bool, error)) error

Ranger represents an abstraction that has ability range over collection item

type SequenceMatcher Uses

type SequenceMatcher struct {
    Terminators   []string
    CaseSensitive bool
    // contains filtered or unexported fields

SequenceMatcher represents a matcher that finds any sequence until find provided terminators

func (*SequenceMatcher) Match Uses

func (m *SequenceMatcher) Match(input string, offset int) int

Match matches a literal in the input, it returns number of character matched.

type ServiceRouter Uses

type ServiceRouter struct {
    // contains filtered or unexported fields

ServiceRouter represents routing rule

func NewServiceRouter Uses

func NewServiceRouter(serviceRouting ...ServiceRouting) *ServiceRouter

NewServiceRouter creates a new service router, is takes list of service routing as arguments

func (*ServiceRouter) Route Uses

func (r *ServiceRouter) Route(response http.ResponseWriter, request *http.Request) error

Route matches service routing by http method , and number of parameters, then it call routing method, and sent back its response.

func (*ServiceRouter) WriteResponse Uses

func (r *ServiceRouter) WriteResponse(encoderFactory EncoderFactory, response interface{}, request *http.Request, responseWriter http.ResponseWriter) error

WriteResponse writes response to response writer, it used encoder factory to encode passed in response to the writer, it sets back request contenttype to response.

type ServiceRouting Uses

type ServiceRouting struct {
    URI                 string      //matching uri
    Handler             interface{} //has to be func
    HTTPMethod          string
    Parameters          []string
    ContentTypeEncoders map[string]EncoderFactory //content type encoder factory
    ContentTypeDecoders map[string]DecoderFactory //content type decoder factory
    HandlerInvoker      HandlerInvoker            //optional function that will be used instead of reflection to invoke a handler.

ServiceRouting represents a simple web services routing rule, which is matched with http request

type StatucCodeAccessor Uses

type StatucCodeAccessor interface {
    GetStatusCode() int

StatucCodeAccessor server side response accessor

type StatucCodeMutator Uses

type StatucCodeMutator interface {
    SetStatusCode(code int)

StatucCodeMutator client side reponse optional interface

type StructField Uses

type StructField struct {
    Owner reflect.Value
    Value reflect.Value
    Type  reflect.StructField

StructField represents a struct field

type StructFieldMeta Uses

type StructFieldMeta struct {
    Name        string `json:"name,omitempty"`
    Type        string `json:"type,omitempty"`
    Required    bool   `json:"required,"`
    Description string `json:"description,omitempty"`

StructFieldMeta represents struct field meta

type StructFields Uses

type StructFields []*StructField

StructFields by name sorter

func (StructFields) Len Uses

func (s StructFields) Len() int

Len is part of sort.Interface.

func (StructFields) Less Uses

func (s StructFields) Less(i, j int) bool

Less is part of sort.Interface.

func (StructFields) Swap Uses

func (s StructFields) Swap(i, j int)

Swap is part of sort.Interface.

type StructMeta Uses

type StructMeta struct {
    Type string

    Fields       []*StructFieldMeta `json:"fields,omitempty"`
    Dependencies []*StructMeta      `json:"dependencies,omitempty"`
    // contains filtered or unexported fields

StructMeta represents struct meta details

func GetStructMeta Uses

func GetStructMeta(source interface{}) *StructMeta

GetStructMeta returns struct meta

func (*StructMeta) Message Uses

func (m *StructMeta) Message() map[string]interface{}

type StructMetaFilter Uses

type StructMetaFilter func(field reflect.StructField) bool


type TimeWindow Uses

type TimeWindow struct {
    Loopback  *Duration
    StartDate string

    EndDate string

    TimeLayout string
    TimeFormat string
    Interval   *Duration
    // contains filtered or unexported fields

TimeWindow represents a time window

func (*TimeWindow) EndTime Uses

func (w *TimeWindow) EndTime() (*time.Time, error)

EndTime returns time window end time

func (*TimeWindow) Layout Uses

func (w *TimeWindow) Layout() string

Layout return time layout

func (*TimeWindow) Range Uses

func (w *TimeWindow) Range(handler func(time time.Time) (bool, error)) error

Range iterates with interval step between start and window end.

func (*TimeWindow) StartTime Uses

func (w *TimeWindow) StartTime() (*time.Time, error)

StartTime returns time window start time

type Token Uses

type Token struct {
    Token   int
    Matched string

Token a matchable input

func ExpectToken Uses

func ExpectToken(tokenizer *Tokenizer, errorMessage string, candidates (*Token, error)

ExpectToken returns the matched token or error

func ExpectTokenOptionallyFollowedBy Uses

func ExpectTokenOptionallyFollowedBy(tokenizer *Tokenizer, first int, errorMessage string, second (*Token, error)

ExpectTokenOptionallyFollowedBy returns second matched token or error if first and second group was not matched

type Tokenizer Uses

type Tokenizer struct {
    Input          string
    Index          int
    InvalidToken   int
    EndOfFileToken int
    // contains filtered or unexported fields

Tokenizer represents a token scanner.

func NewTokenizer Uses

func NewTokenizer(input string, invalidToken int, endOfFileToken int, matcher map[int]Matcher) *Tokenizer

NewTokenizer creates a new NewTokenizer, it takes input, invalidToken, endOfFileToeken, and matchers.

func (*Tokenizer) Next Uses

func (t *Tokenizer) Next(candidate int) *Token

Next tries to match a candidate, it returns token if imatching is successful.

func (*Tokenizer) Nexts Uses

func (t *Tokenizer) Nexts(candidates *Token

Nexts matches the first of the candidates

type ToolboxHTTPClient Uses

type ToolboxHTTPClient struct {
    // contains filtered or unexported fields

ToolboxHTTPClient contains preconfigured http client

func NewToolboxHTTPClient Uses

func NewToolboxHTTPClient(options ...*HttpOptions) (*ToolboxHTTPClient, error)

NewToolboxHTTPClient instantiate new client with provided options

func (*ToolboxHTTPClient) Request Uses

func (c *ToolboxHTTPClient) Request(method, url string, request, response interface{}, encoderFactory EncoderFactory, decoderFactory DecoderFactory) (err error)

Request sends http request using the existing client

type TypeInfo Uses

type TypeInfo struct {
    Name                   string
    Package                string
    FileName               string
    Comment                string
    IsSlice                bool
    IsStruct               bool
    IsInterface            bool
    IsDerived              bool
    ComponentType          string
    IsPointerComponentType bool
    Derived                string
    Settings               map[string]string
    // contains filtered or unexported fields

TypeInfo represents a struct info

func NewTypeInfo Uses

func NewTypeInfo(name string) *TypeInfo

NewTypeInfo creates a new struct info

func (*TypeInfo) AddFields Uses

func (s *TypeInfo) AddFields(fields ...*FieldInfo)

AddFields appends fileds to structinfo

func (*TypeInfo) AddReceivers Uses

func (s *TypeInfo) AddReceivers(receivers ...*FunctionInfo)

AddReceivers adds receiver for the struct

func (*TypeInfo) Field Uses

func (s *TypeInfo) Field(name string) *FieldInfo

Field returns filedinfo for supplied file name

func (*TypeInfo) Fields Uses

func (s *TypeInfo) Fields() []*FieldInfo

Fields returns all fields

func (*TypeInfo) HasField Uses

func (s *TypeInfo) HasField(name string) bool

HasField returns true if struct has passed in field.

func (*TypeInfo) HasReceiver Uses

func (s *TypeInfo) HasReceiver(name string) bool

HasReceiver returns true if receiver is defined for struct

func (*TypeInfo) Receiver Uses

func (s *TypeInfo) Receiver(name string) *FunctionInfo

Receiver returns receiver for passed in name

func (*TypeInfo) Receivers Uses

func (s *TypeInfo) Receivers() []*FunctionInfo

Receivers returns struct functions

type UnMarshaler Uses

type UnMarshaler interface {
    //Unmarshal converts a struct to bytes
    Unmarshal(data []byte) error

UnMarshaler represent an struct that can be converted to bytes

type UnexportedFieldHandler Uses

type UnexportedFieldHandler func(structField *StructField) bool

UnexportedFieldHandler represents unexported field handler

type ValueProvider Uses

type ValueProvider interface {
    //Get returns a value for passed in context and arguments. Context can be used to manage state.
    Get(context Context, arguments ...interface{}) (interface{}, error)

ValueProvider represents a value provider

func NewBetweenPredicateValueProvider Uses

func NewBetweenPredicateValueProvider() ValueProvider

NewBetweenPredicateValueProvider returns a new between value provider

func NewCastedValueProvider Uses

func NewCastedValueProvider() ValueProvider

NewCastedValueProvider return a provider that return casted value type

func NewConstValueProvider Uses

func NewConstValueProvider(value string) ValueProvider

NewConstValueProvider returns a provider that returns a nil

func NewCurrentDateProvider Uses

func NewCurrentDateProvider() ValueProvider

NewCurrentDateProvider returns a provider that returns current date in the format yyyymmdd, i.e. 20170205

func NewCurrentTimeProvider Uses

func NewCurrentTimeProvider() ValueProvider

NewCurrentTimeProvider returns a provder that returns time.Now()

func NewDateOfBirthrovider Uses

func NewDateOfBirthrovider() ValueProvider

NewDateOfBirthValueProvider provider for computing date for supplied expected age, month and day

func NewDictionaryProvider Uses

func NewDictionaryProvider(contextKey interface{}) ValueProvider

NewDictionaryProvider creates a new Dictionary provider, it takes a key context that is a MapDictionary pointer

func NewEnvValueProvider Uses

func NewEnvValueProvider() ValueProvider

NewEnvValueProvider returns a provider that returns a value of env variables.

func NewFileValueProvider Uses

func NewFileValueProvider(trim bool) ValueProvider

NewFileValueProvider create new file value provider

func NewNilValueProvider Uses

func NewNilValueProvider() ValueProvider

NewNilValueProvider returns a provider that returns a nil

func NewTimeDiffProvider Uses

func NewTimeDiffProvider() ValueProvider

NewTimeDiffProvider returns a provider that delta, time unit and optionally format format as java date format or unix or timestamp

func NewWeekdayProvider Uses

func NewWeekdayProvider() ValueProvider

func NewWithinSecPredicateValueProvider Uses

func NewWithinSecPredicateValueProvider() ValueProvider

NewWithinSecPredicateValueProvider returns a new within second value provider

type ValueProviderRegistry Uses

type ValueProviderRegistry interface {
    Register(name string, valueProvider ValueProvider)

    Contains(name string) bool

    Names() []string

    Get(name string) ValueProvider

ValueProviderRegistry registry of value providers

func NewValueProviderRegistry Uses

func NewValueProviderRegistry() ValueProviderRegistry

NewValueProviderRegistry create new NewValueProviderRegistry

type Zeroable Uses

type Zeroable interface {
    //IsZero returns true, if value of object was zeroed.
    IsZero() bool

Zeroable represents object that can call IsZero


storagePackage storage define abstract storage operation Deprecated - please use API instead This package is frozen and no new functionality will be added, and future removal takes place.

Package toolbox imports 35 packages (graph) and is imported by 119 packages. Updated 2020-02-11. Refresh now. Tools for package owners.