goutils

package module
v0.0.0-...-fae163d Latest Latest
Warning

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

Go to latest
Published: May 29, 2026 License: Apache-2.0 Imports: 23 Imported by: 53

README

goutils

goutils includes common functions for other Go packages.

Documentation

Overview

Package goutils includes common functions for other Go packages.

Index

Constants

View Source
const (
	// YAMLNullTag represents a constant for a YAML null tag.
	YAMLNullTag = "!!null"
	// YAMLBoolTag represents a constant for a YAML boolean tag.
	YAMLBoolTag = "!!bool"
	// YAMLStrTag represents a constant for a YAML string tag.
	YAMLStrTag = "!!str"
	// YAMLIntTag represents a constant for a YAML integer tag.
	YAMLIntTag = "!!int"
	// YAMLFloatTag represents a constant for a YAML float tag.
	YAMLFloatTag = "!!float"
	// YAMLTimestampTag represents a constant for a YAML timestamp tag.
	YAMLTimestampTag = "!!timestamp"
	// YAMLSeqTag represents a constant for a YAML sequence tag.
	YAMLSeqTag = "!!seq"
	// YAMLMapTag represents a constant for a YAML map tag.
	YAMLMapTag = "!!map"
	// YAMLBinaryTag represents a constant for a YAML binary tag.
	YAMLBinaryTag = "!!binary"
	// YAMLMergeTag represents a constant for a YAML merge tag.
	YAMLMergeTag = "!!merge"
)
View Source
const NullStr = "null"

NullStr represents an enum for a null value.

Variables

View Source
var (
	// ErrDurationOutOfRange occurs when the duration int64 value is out of range.
	ErrDurationOutOfRange = errors.New("duration out of range")
	// ErrDurationEmpty occurs when the duration string is empty.
	ErrDurationEmpty = errors.New("empty duration string")
	// ErrInvalidDurationString occurs when the duration string is invalid.
	ErrInvalidDurationString = errors.New("not a valid duration string")
	// ErrUnknownDurationUnit occurs when the duration unit is unknown.
	ErrUnknownDurationUnit = errors.New("unknown duration unit")
	// ErrInvalidDateTimeString occurs when the date time string is invalid.
	ErrInvalidDateTimeString = errors.New("not a valid date time string")
)
View Source
var (
	// ErrInvalidURI represents an invalid uri error.
	ErrInvalidURI = errors.New("invalid URI")
	// ErrBlockedIP occurs when the IP is blocked.
	ErrBlockedIP = errors.New("ip is blocked")
	// ErrInvalidURLScheme represents an invalid URL scheme error.
	ErrInvalidURLScheme = errors.New("invalid url scheme")
	// ErrInvalidSubnet occurs when the subnet string is invalid.
	ErrInvalidSubnet = errors.New("invalid IP or subnet")
	// ErrInvalidSlug represents an invalid slug error.
	ErrInvalidSlug = errors.New("invalid slug")
	// ErrMalformedJSON occurs when the JSON syntax or value is malformed.
	ErrMalformedJSON = errors.New("malformed JSON")
	// ErrStringNull occurs when the string value is nil.
	ErrStringNull = errors.New("string value must not be null")
	// ErrMalformedString occurs when the string value is malformed.
	ErrMalformedString = errors.New("malformed string")
	// ErrMalformedStringSlice occurs when the string slice is malformed.
	ErrMalformedStringSlice = errors.New("malformed string slice")
	// ErrStringSliceNull occurs when the string slice is nil.
	ErrStringSliceNull = errors.New("string slice must not be null")
	// ErrNumberNull occurs when the number value is nil.
	ErrNumberNull = errors.New("number value must not be null")
	// ErrMalformedNumber occurs when the number value is malformed.
	ErrMalformedNumber = errors.New("malformed number")
	// ErrMalformedNumberSlice occurs when the number slice is malformed.
	ErrMalformedNumberSlice = errors.New("malformed number slice")
	// ErrBooleanNull occurs when the boolean value is nil.
	ErrBooleanNull = errors.New("boolean value must not be null")
	// ErrMalformedBoolean occurs when the boolean value is malformed.
	ErrMalformedBoolean = errors.New("malformed boolean")
	// ErrMalformedBooleanSlice occurs when the boolean slice is malformed.
	ErrMalformedBooleanSlice = errors.New("malformed boolean slice")
	// ErrBooleanSliceNull occurs when the boolean slice is nil.
	ErrBooleanSliceNull = errors.New("boolean slice must not be null")
	// ErrMalformedYAML occurs when the YAML syntax or structure is malformed.
	ErrMalformedYAML = errors.New("malformed YAML")
)

Functions

func AsBoolean

func AsBoolean(value any) (bool, error)

AsBoolean tries to cast an unknown value to a bool value.

func AsBooleanReflection

func AsBooleanReflection(value reflect.Value) (bool, error)

AsBooleanReflection tries to cast a boolean value from reflection.

func AsBooleanSlice

func AsBooleanSlice(value any) ([]bool, error)

AsBooleanSlice tries to cast a boolean slice from an unknown value.

func AsNullableBoolean

func AsNullableBoolean(value any) (*bool, error)

AsNullableBoolean tries to cast an unknown value to a bool pointer.

func AsNullableBooleanReflection

func AsNullableBooleanReflection(value reflect.Value) (*bool, error)

AsNullableBooleanReflection tries to cast a nullable boolean value from reflection.

func AsNullableBooleanSlice

func AsNullableBooleanSlice(value any) (*[]bool, error)

AsNullableBooleanSlice tries to cast a nullable boolean slice from an unknown value.

func AsNullableNumber

func AsNullableNumber[T ~int | ~int8 | ~int16 | ~int32 | ~int64 | ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~float32 | ~float64](
	value any,
) (*T, error)

AsNullableNumber tries to cast an unknown value to a typed number.

func AsNullableNumberReflection

func AsNullableNumberReflection[T ~int | ~int8 | ~int16 | ~int32 | ~int64 | ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~float32 | ~float64](
	value reflect.Value,
) (*T, error)

AsNullableNumberReflection tries to cast a nullable numeric value (int, uint, or float) using reflection.

func AsNumber

func AsNumber[T ~int | ~int8 | ~int16 | ~int32 | ~int64 | ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~float32 | ~float64](
	value any,
) (T, error)

AsNumber tries to cast an unknown value to a typed number.

func AsNumberReflection

func AsNumberReflection[T ~int | ~int8 | ~int16 | ~int32 | ~int64 | ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~float32 | ~float64](
	value reflect.Value,
) (T, error)

AsNumberReflection tries to cast the number value using reflection.

func AsNumberSlice

func AsNumberSlice[T ~int | ~int8 | ~int16 | ~int32 | ~int64 | ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~float32 | ~float64](
	value any,
) ([]T, error)

AsNumberSlice tries to cast a number slice from an unknown value.

func AsNumberSliceReflection

func AsNumberSliceReflection[T ~int | ~int8 | ~int16 | ~int32 | ~int64 | ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~float32 | ~float64](
	reflectValue reflect.Value,
) ([]T, error)

AsNumberSliceReflection tries to cast a number slice from a reflection value.

func CatchWarnContextErrorFunc

func CatchWarnContextErrorFunc(fn func(ctx context.Context) error)

CatchWarnContextErrorFunc catches the closer function with context and prints error with the WARN level.

func CatchWarnErrorFunc

func CatchWarnErrorFunc(fn func() error)

CatchWarnErrorFunc catches the closer function and prints error with the WARN level.

func CloseResponse

func CloseResponse(resp *http.Response)

CloseResponse gracefully closes the HTTP response and tries to drain the body if it exists. It makes a best effort to reuse the HTTP connection.

func DecodeBoolean

func DecodeBoolean(value any) (bool, error)

DecodeBoolean tries to convert an unknown value to a bool value.

func DecodeBooleanReflection

func DecodeBooleanReflection(value reflect.Value) (bool, error)

DecodeBooleanReflection decodes a boolean value from reflection.

func DecodeBooleanSlice

func DecodeBooleanSlice(value any) ([]bool, error)

DecodeBooleanSlice decodes a boolean slice from an unknown value.

func DecodeNullableBoolean

func DecodeNullableBoolean(value any) (*bool, error)

DecodeNullableBoolean tries to convert an unknown value to a bool pointer.

func DecodeNullableBooleanReflection

func DecodeNullableBooleanReflection(value reflect.Value) (*bool, error)

DecodeNullableBooleanReflection decodes a nullable boolean value from reflection.

func DecodeNullableBooleanSlice

func DecodeNullableBooleanSlice(value any) (*[]bool, error)

DecodeNullableBooleanSlice decodes a nullable boolean slice from an unknown value.

func DecodeNullableNumber

func DecodeNullableNumber[T ~int | ~int8 | ~int16 | ~int32 | ~int64 | ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~float32 | ~float64](
	value any,
) (*T, error)

DecodeNullableNumber tries to convert an unknown value to a typed number.

func DecodeNullableNumberReflection

func DecodeNullableNumberReflection[T ~int | ~int8 | ~int16 | ~int32 | ~int64 | ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~float32 | ~float64](
	value reflect.Value,
) (*T, error)

DecodeNullableNumberReflection decodes a nullable numeric value (int, uint, or float) using reflection.

func DecodeNullableString

func DecodeNullableString(value any) (*string, error)

DecodeNullableString tries to convert an unknown value to a string pointer.

func DecodeNullableStringReflection

func DecodeNullableStringReflection(value reflect.Value) (*string, error)

DecodeNullableStringReflection decodes a nullable string from reflection value.

func DecodeNumber

func DecodeNumber[T ~int | ~int8 | ~int16 | ~int32 | ~int64 | ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~float32 | ~float64](
	value any,
) (T, error)

DecodeNumber tries to convert an unknown value to a typed number.

func DecodeNumberReflection

func DecodeNumberReflection[T ~int | ~int8 | ~int16 | ~int32 | ~int64 | ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~float32 | ~float64](
	value reflect.Value,
) (T, error)

DecodeNumberReflection decodes the number value using reflection.

func DecodeNumberSlice

func DecodeNumberSlice[T ~int | ~int8 | ~int16 | ~int32 | ~int64 | ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~float32 | ~float64](
	value any,
) ([]T, error)

DecodeNumberSlice decodes a number slice from an unknown value.

func DecodeNumberSliceReflection

func DecodeNumberSliceReflection[T ~int | ~int8 | ~int16 | ~int32 | ~int64 | ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~float32 | ~float64](
	reflectValue reflect.Value,
) ([]T, error)

DecodeNumberSliceReflection decodes a number slice from a reflection value.

func DecodeString

func DecodeString(value any) (string, error)

DecodeString tries to convert an unknown value to a string value.

func DecodeStringReflection

func DecodeStringReflection(value reflect.Value) (string, error)

DecodeStringReflection decodes a string from reflection value.

func DecodeStringSlice

func DecodeStringSlice(value any) ([]string, error)

DecodeStringSlice decodes a string slice from an unknown value.

func DecodeStringSliceReflection

func DecodeStringSliceReflection(reflectValue reflect.Value) ([]string, error)

DecodeStringSliceReflection decodes a string slice from a reflection value.

func DeepEqual

func DeepEqual[T any](
	x T,
	y any,
	omitZero bool,
) bool

DeepEqual checks if both values are equal recursively.

func DeepEqualPtr

func DeepEqualPtr[T any](x, y *T, omitZero bool) bool

DeepEqualPtr checks if both pointers are equal recursively.

func EqualComparableAny

func EqualComparableAny[T comparable](x T, y any) bool

EqualComparableAny checks if the y is comparable and equal x.

func EqualComparableAnyPtr

func EqualComparableAnyPtr[T comparable](x *T, y any) bool

EqualComparableAnyPtr checks if the y is comparable and equal the pointer x.

func EqualComparablePtr

func EqualComparablePtr[T comparable](x, y *T) bool

EqualComparablePtr checks if the y is comparable and equal the pointer x.

func EqualComparableSlice

func EqualComparableSlice[T comparable](x []T, y any, omitZero bool) bool

EqualComparableSlice checks if the y is comparable and equal x.

func EqualMap

func EqualMap[K comparable, V any](mapA, mapB map[K]V, omitZero bool) bool

EqualMap checks if both maps' elements are matched.

func EqualMapPointer

func EqualMapPointer[K comparable, V Equaler[V]](
	mapA, mapB map[K]*V,
	omitZero bool,
) bool

EqualMapPointer checks if both maps' pointer elements are matched.

func EqualPtr

func EqualPtr[T Equaler[T]](a, b *T) bool

EqualPtr checks if the value of both pointers are equal.

func EqualSlice

func EqualSlice[T any](sliceA, sliceB []T, omitZero bool) bool

EqualSlice checks if both slices' elements are matched.

func EqualSlicePtr

func EqualSlicePtr[T Equaler[T]](sliceA, sliceB []*T) bool

EqualSlicePtr checks if both slices' pointer elements are matched.

func EqualSliceSorted

func EqualSliceSorted[T cmp.Ordered](sliceA, sliceB []T) bool

EqualSliceSorted checks if both slices's elements are matched with sorted order.

func ExtractHeaders

func ExtractHeaders(headers http.Header) map[string]string

ExtractHeaders converts the http.Header to string map with lowercase header names.

func FileReaderFromPath

func FileReaderFromPath(
	ctx context.Context,
	filePath string,
	options ...DownloadFileOption,
) (io.ReadCloser, string, error)

FileReaderFromPath reads content from either a local filesystem path or an HTTP/HTTPS URL.

Supported URL schemes are "http" and "https". If the provided path parses as a URL with one of these schemes, an HTTP GET request is issued using http.DefaultClient without an explicit timeout configured. Callers that require timeouts or custom HTTP behavior should arrange this outside of this helper.

For other schemes, or if the input does not represent an http/https URL, the value is treated as a filesystem path, cleaned with filepath.Clean, and opened via os.Open.

The caller is responsible for closing the returned io.ReadCloser when finished with it.

func FormatScalar

func FormatScalar(
	value any,
) (string, bool)

FormatScalar converts an arbitrary value to its string representation.

It handles the following cases:

  • For nil values, it returns the provided NullStr.
  • For primitive types (bool, string, integers, floats, complex), it uses the appropriate formatting.
  • For time.Time and *time.Time, it uses the standard time formatting.
  • For types implementing fmt.Stringer, it uses their String() method.
  • For pointers, it dereferences and formats the underlying value, or returns NullStr if nil.
  • For unsupported types, return an empty string and a false value.

The NullStr parameter specifies the string to return for nil values or nil pointers.

func FormatScalarReflection

func FormatScalarReflection(reflectValue reflect.Value) (string, bool)

FormatScalarReflection converts a reflection value to its string representation.

func GetNodeValueFromYAMLMap

func GetNodeValueFromYAMLMap(node *yaml.Node, key string) (*yaml.Node, error)

GetNodeValueFromYAMLMap gets the node value from a YAML map node.

func GetSortedKeys

func GetSortedKeys[K cmp.Ordered, V any](input map[K]V) []K

GetSortedKeys extract and sort keys of a map.

func GetStringValueFromYAMLMap

func GetStringValueFromYAMLMap(node *yaml.Node, key string) (*string, error)

GetStringValueFromYAMLMap gets the string value from a YAML map node.

func HasStringPrefixFold

func HasStringPrefixFold(input string, prefix string) bool

HasStringPrefixFold check if a string has a case-insensitive prefix.

func HasStringSuffixFold

func HasStringSuffixFold(input string, suffix string) bool

HasStringSuffixFold checks if a string has a case-insensitive suffix.

func IsDigit

func IsDigit[C byte | rune](c C) bool

IsDigit checks if the character is a digit.

func IsDigitString

func IsDigitString(value string) bool

IsDigitString checks if every character in the string is an ASCII digit.

func IsIntegerString

func IsIntegerString(value string) bool

IsIntegerString checks if the input string can be parsed to an integer.

func IsLowerAlphabet

func IsLowerAlphabet[C byte | rune](c C) bool

IsLowerAlphabet checks if the character is a lowercase alphabet.

func IsMetaCharacter

func IsMetaCharacter[C byte | rune](c C) bool

IsMetaCharacter checks if the character is a word character. A word character is a character a-z, A-Z, 0-9, including _ (underscore) and - (hyphen).

func IsNil

func IsNil(value any) bool

IsNil safely checks if a value is nil.

func IsUpperAlphabet

func IsUpperAlphabet[C byte | rune](c C) bool

IsUpperAlphabet checks if the character is an uppercase alphabet.

func IsZero

func IsZero[T any](value T) bool

IsZero checks if the value is zero.

func IsZeroPtr

func IsZeroPtr[T any](ptr *T) bool

IsZeroPtr checks if the pointer is zero.

func LoadMultiJSONDocumentStream

func LoadMultiJSONDocumentStream[T any](reader io.Reader) ([]T, error)

LoadMultiJSONDocumentStream loads multi-document JSON from a reader stream.

func LoadMultiYAMLDocumentStream

func LoadMultiYAMLDocumentStream[T any](reader io.Reader) ([]T, error)

LoadMultiYAMLDocumentStream loads multi-documents YAML from a reader stream.

func Map

func Map[T, M any](input []T, f func(T) M) []M

Map applies a function to each element of a slice and returns a new slice with the results. T is the type of the input slice elements. M is the type of the output slice elements.

func NewUUIDv7

func NewUUIDv7() uuid.UUID

NewUUIDv7 creates a random UUID version 7. Fallback to v4 if there is error.

func ParseDateTimeNative

func ParseDateTimeNative[B []byte | string](input B) (time.Time, error)

ParseDateTimeNative parses date time in RFC 3339 or ISO 8601 format formats.

func ParseHTTPURL

func ParseHTTPURL(input string) (*url.URL, error)

ParseHTTPURL parses and validate the input string to have http(s) scheme.

func ParseIntInRange

func ParseIntInRange[B []byte | string](s B, minValue int, maxValue int) (int, bool)

ParseIntInRange parses s as an integer and verifies that it is within some range. If it is invalid or out-of-range, it sets ok to false and returns the min value.

func ParsePathOrHTTPURL

func ParsePathOrHTTPURL(input string) (*url.URL, error)

ParsePathOrHTTPURL validates and parses a path or HTTP URL.

func ParsePathOrURL

func ParsePathOrURL(input string) (*url.URL, error)

ParsePathOrURL validates and parses a path or URL.

func ParseSubnet

func ParseSubnet(value string) (*net.IPNet, error)

ParseSubnet parses the subnet from a raw string.

func PtrToNumberSlice

func PtrToNumberSlice[T1, T2 ~int | ~int8 | ~int16 | ~int32 | ~int64 | ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~float32 | ~float64](
	inputs []*T1,
) ([]T2, error)

PtrToNumberSlice converts a slice of number pointers to a slice of values. Returns nil, nil if inputs is nil. Returns an error if any element in the slice is nil.

func QuoteBytes

func QuoteBytes[T string | []byte](input T) []byte

QuoteBytes add double quotes surround the string and convert it to bytes.

func ReadJSONOrYAMLFile

func ReadJSONOrYAMLFile[T any](
	ctx context.Context,
	filePath string,
	options ...DownloadFileOption,
) (*T, error)

ReadJSONOrYAMLFile reads and decodes a JSON or YAML document from the given source, which may be a local file path or an HTTP/HTTPS URL.

func ReadMultiFromJSONOrYAMLFile

func ReadMultiFromJSONOrYAMLFile[T any](
	ctx context.Context,
	filePath string,
	options ...DownloadFileOption,
) ([]T, error)

ReadMultiFromJSONOrYAMLFile reads and decodes multiple JSON or YAML documents from the given source, which may be a local file path or an HTTP/HTTPS URL.

func StringContainsCTLByte

func StringContainsCTLByte(s string) bool

StringContainsCTLByte reports whether s contains any ASCII control character.

func ToAnyMap

func ToAnyMap[K comparable, V any](input map[K]V) map[K]any

ToAnyMap converts a typed map to a map[K]any.

func ToAnySlice

func ToAnySlice[T any](inputs []T) []any

ToAnySlice converts the a typed slice to any slice.

func ToNumberSlice

func ToNumberSlice[T1, T2 ~int | ~int8 | ~int16 | ~int32 | ~int64 | ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~float32 | ~float64](
	inputs []T1,
) []T2

ToNumberSlice converts the element type of a number slice.

func ToString

func ToString(value any) string

ToString converts an arbitrary value to its string representation.

It handles the following cases:

  • For nil values, it returns the provided NullStr.
  • For primitive types (bool, string, integers, floats, complex), it uses the appropriate formatting.
  • For time.Time, time.Duration, and their pointer types, it uses the standard time formatting.
  • For types implementing fmt.Stringer, it uses their String() method.
  • For pointers, it dereferences and formats the underlying value, or returns NullStr if nil.
  • For all other types, it uses a best-effort formatting strategy.

If JSON marshaling fails, it returns an error.

The NullStr parameter specifies the string to return for nil values or nil pointers.

func UnwrapPointerFromReflectValue

func UnwrapPointerFromReflectValue(reflectValue reflect.Value) (reflect.Value, bool)

UnwrapPointerFromReflectValue recursively unwraps pointers from a reflect value. Returns the unwrapped value and true if the value is valid and not nil, or false if the value is nil or invalid.

func ValidateIP

func ValidateIP(ip net.IP, options ValidateIPOptions) error

ValidateIP checks if the IP is valid for SSRF protection. Note: the allowed ranges option is the highest priority to bypass other rules.

func ValidateIPOrDomain

func ValidateIPOrDomain(
	ctx context.Context,
	domainOrIP string,
	options ValidateIPOptions,
) error

ValidateIPOrDomain checks if the IP string or IP of domain is valid for SSRF protection. If the input string is a domain, lookup the IP from it before validation.

func ValidateURL

func ValidateURL(ctx context.Context, uri *url.URL, options ValidateHTTPURLOptions) error

ValidateURL parses and validates URL.

func ValidateURLString

func ValidateURLString(
	ctx context.Context,
	urlStr string,
	options ValidateHTTPURLOptions,
) (*url.URL, error)

ValidateURLString parses and validates URL from a string. Returns the parsed URL and an error.

Types

type AllOrListString

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

AllOrListString is a type that represents either a wildcard ("*") meaning "all items", or a specific list of strings. This is useful for configuration fields where you want to allow users to specify either all possible values (using "*") or a subset of values.

func NewAll

func NewAll() AllOrListString

NewAll creates an AllOrListString that accepts all values.

func NewStringList

func NewStringList(list []string) AllOrListString

NewStringList creates an AllOrListString with a list of static strings.

func (AllOrListString) Contains

func (j AllOrListString) Contains(input string) bool

Contains reports whether the input value is accepted. It returns true if the wildcard "all" is set or if the input value is present in the list.

func (AllOrListString) Equal

func (j AllOrListString) Equal(target AllOrListString) bool

Equal checks if the target value is equal.

func (AllOrListString) IsAll

func (j AllOrListString) IsAll() bool

IsAll returns true if the value represents the wildcard ("all").

func (AllOrListString) IsZero

func (j AllOrListString) IsZero() bool

IsZero returns true if the current instance is in its zero state (neither all nor list is set).

func (AllOrListString) List

func (j AllOrListString) List() []string

List returns the list of strings, or nil if IsAll() is true.

func (AllOrListString) Map

func (j AllOrListString) Map(f func(s string) string) AllOrListString

Map returns a new AllOrListString with transformed list string.

func (AllOrListString) MarshalJSON

func (j AllOrListString) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

func (AllOrListString) MarshalYAML

func (j AllOrListString) MarshalYAML() (any, error)

MarshalYAML implements the custom behavior for the yaml.Marshaler interface. If the wildcard state is set (all == true), it serializes as the string "*". Otherwise, it serializes the list as a YAML sequence.

func (AllOrListString) String

func (j AllOrListString) String() string

String implements the custom behavior for the fmt.Stringer interface.

func (*AllOrListString) UnmarshalJSON

func (j *AllOrListString) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler.

func (*AllOrListString) UnmarshalText

func (j *AllOrListString) UnmarshalText(text []byte) error

UnmarshalText implements the custom behavior for the encoding.TextUnmarshaler interface.

func (*AllOrListString) UnmarshalYAML

func (j *AllOrListString) UnmarshalYAML(value *yaml.Node) error

UnmarshalYAML implements custom deserialization for the yaml.Unmarshaler interface. If the YAML value is the string "*", it is treated as a wildcard and sets 'all' to true and 'list' to nil. Otherwise, it expects a list of strings and sets 'list' accordingly, with 'all' set to false.

type AllOrListWildcardString

type AllOrListWildcardString struct {
	AllOrListString
	// contains filtered or unexported fields
}

AllOrListWildcardString is a type that represents either a wildcard ("*") meaning "all items", or a specific list of strings. Accept a star (*) in any string for sub-matching patterns.

func NewAllOrListWildcardStringFromStrings

func NewAllOrListWildcardStringFromStrings(values []string) AllOrListWildcardString

NewAllOrListWildcardStringFromStrings constructs an AllOrListWildcardString from the provided list of strings, parsing any wildcard patterns using the same logic as JSON/YAML unmarshaling.

func NewAllWildcard

func NewAllWildcard() AllOrListWildcardString

NewAllWildcard creates an AllOrListWildcardString that represents all items ("*").

func (AllOrListWildcardString) Contains

func (j AllOrListWildcardString) Contains(input string) bool

Contains reports whether the input value is contained in this set. It returns true if the embedded AllOrListString is in the "all" state, or if the input value is present in its static list, or if the input matches any of the configured wildcard patterns.

func (AllOrListWildcardString) Equal

Equal checks if the target value is equal.

func (AllOrListWildcardString) IsZero

func (j AllOrListWildcardString) IsZero() bool

IsZero returns true if the current instance is in its zero state (neither all nor list is set).

func (AllOrListWildcardString) MarshalJSON

func (j AllOrListWildcardString) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

func (AllOrListWildcardString) MarshalYAML

func (j AllOrListWildcardString) MarshalYAML() (any, error)

MarshalYAML implements the custom behavior for the yaml.Marshaler interface. If the wildcard state is set (all == true), it serializes as the string "*". Otherwise, it serializes the list as a YAML sequence.

func (AllOrListWildcardString) String

func (j AllOrListWildcardString) String() string

String implements the custom behavior for the fmt.Stringer interface.

func (*AllOrListWildcardString) UnmarshalJSON

func (j *AllOrListWildcardString) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler.

func (*AllOrListWildcardString) UnmarshalYAML

func (j *AllOrListWildcardString) UnmarshalYAML(value *yaml.Node) error

UnmarshalYAML implements custom deserialization for the yaml.Unmarshaler interface. If the YAML value is the string "*", it is treated as a wildcard and sets 'all' to true and 'list' to nil. Otherwise, it expects a list of strings and sets 'list' accordingly, with 'all' set to false.

func (AllOrListWildcardString) Wildcards

func (j AllOrListWildcardString) Wildcards() []Wildcard

Wildcards returns the list of wildcards, or nil if IsAll() is true.

type Doer

type Doer interface {
	// Do sends an HTTP request and returns an HTTP response, following policy
	// (such as redirects, cookies, auth) as configured on the client.
	Do(req *http.Request) (*http.Response, error)
}

Doer abstracts an interface for sending HTTP requests.

type DownloadFileOption

type DownloadFileOption func(opts *downloadFileOptions)

DownloadFileOption abstracts a function to configure options for loading files.

func DownloadFileExcludingPaths

func DownloadFileExcludingPaths(paths []string) DownloadFileOption

DownloadFileExcludingPaths creates an option to set a list of paths to be excluded.

func DownloadFileIncludingPaths

func DownloadFileIncludingPaths(paths []string) DownloadFileOption

DownloadFileIncludingPaths creates an option to set a list of paths to be included.

func DownloadFileWithAllowedHosts

func DownloadFileWithAllowedHosts(hosts []string) DownloadFileOption

DownloadFileWithAllowedHosts creates an option to set a list of allowed hosts for URL.

func DownloadFileWithBlockedHosts

func DownloadFileWithBlockedHosts(hosts []string) DownloadFileOption

DownloadFileWithBlockedHosts creates an option to set a list of blocked hosts for URL.

func DownloadFileWithHTTPClient

func DownloadFileWithHTTPClient(client Doer) DownloadFileOption

DownloadFileWithHTTPClient creates an option to set a custom HTTP client to load file.

type Duration

type Duration time.Duration //nolint:recvcheck

Duration wraps time.Duration. It is used to parse and format custom duration strings from YAML, JSON, and text formats.

func ParseDuration

func ParseDuration(s string) (Duration, error)

ParseDuration parses a string into a time.Duration, assuming that a year always has 365d, a week always has 7d, and a day always has 24h. Negative durations are not supported.

func (Duration) Abs

func (d Duration) Abs() Duration

Abs returns the absolute value of the current duration.

func (Duration) Hours

func (d Duration) Hours() float64

Hours returns the duration as a floating point number of hours.

func (Duration) MarshalJSON

func (d Duration) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface.

func (Duration) MarshalText

func (d Duration) MarshalText() ([]byte, error)

MarshalText implements the encoding.TextMarshaler interface.

func (Duration) Microseconds

func (d Duration) Microseconds() int64

Microseconds returns the duration as an integer microsecond count.

func (Duration) Milliseconds

func (d Duration) Milliseconds() int64

Milliseconds returns the duration as an integer millisecond count.

func (Duration) Minutes

func (d Duration) Minutes() float64

Minutes returns the duration as a floating point number of minutes.

func (Duration) Nanoseconds

func (d Duration) Nanoseconds() int64

Nanoseconds returns the duration as an integer nanosecond count.

func (Duration) Round

func (d Duration) Round(m Duration) Duration

Round returns the result of rounding d to the nearest multiple of m. The rounding behavior for halfway values is to round away from zero. If the result exceeds the maximum (or minimum) value that can be stored in a Duration, Round returns the maximum (or minimum) duration. If m <= 0, Round returns d unchanged.

func (Duration) Seconds

func (d Duration) Seconds() float64

Seconds returns the duration as a floating point number of seconds.

func (*Duration) Set

func (d *Duration) Set(s string) error

Set implements pflag/flag.Value.

func (Duration) String

func (d Duration) String() string

String implements the fmt.Stringer interface.

func (Duration) Truncate

func (d Duration) Truncate(m Duration) Duration

Truncate returns the result of rounding d toward zero to a multiple of m. If m <= 0, Truncate returns d unchanged.

func (*Duration) Type

func (*Duration) Type() string

Type implements pflag.Value.

func (*Duration) UnmarshalJSON

func (d *Duration) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaler interface.

func (*Duration) UnmarshalText

func (d *Duration) UnmarshalText(text []byte) error

UnmarshalText implements the encoding.TextUnmarshaler interface.

type Equaler

type Equaler[T any] interface {
	// Equal checks if the target value is equal.
	Equal(target T) bool
}

Equaler abstracts an interface to check the equality.

type HTTPErrorWithExtensions

type HTTPErrorWithExtensions struct {
	httperror.HTTPError

	// Additional members that are specific to that problem type.
	Extensions map[string]any
}

HTTPErrorWithExtensions is the data structure of an HTTP error with extensions. that follows the RFC 9457 specification. The schema is inspired by Swagger API specification.

func NewHTTPErrorWithExtensions

func NewHTTPErrorWithExtensions(
	err httperror.HTTPError,
	extensions map[string]any,
) *HTTPErrorWithExtensions

NewHTTPErrorWithExtensions creates a new RFC 9457 error with extensions.

func (HTTPErrorWithExtensions) Error

func (e HTTPErrorWithExtensions) Error() string

Error implements the error interface for HTTPErrorWithExtensions.

func (HTTPErrorWithExtensions) MarshalJSON

func (e HTTPErrorWithExtensions) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface.

func (*HTTPErrorWithExtensions) UnmarshalJSON

func (e *HTTPErrorWithExtensions) UnmarshalJSON(
	data []byte,
) error

UnmarshalJSON implements the json.Unmarshaler interface.

type IsZeroer

type IsZeroer interface {
	IsZero() bool
}

IsZeroer abstracts an interface to check if the instance is zero.

type RegexpMatcher

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

RegexpMatcher wraps the regexp.Regexp with a string for simple matching.

func MustRegexpMatcher

func MustRegexpMatcher(input string) *RegexpMatcher

MustRegexpMatcher creates a RegexpMatcher from a raw string. Panic if error.

func NewRegexpMatcher

func NewRegexpMatcher(input string) (*RegexpMatcher, error)

NewRegexpMatcher creates a RegexpMatcher from a raw string.

func (RegexpMatcher) Equal

func (j RegexpMatcher) Equal(target RegexpMatcher) bool

Equal checks if the target value is equal.

func (RegexpMatcher) IsZero

func (j RegexpMatcher) IsZero() bool

IsZero returns true if the current instance is in its zero state.

func (RegexpMatcher) MarshalJSON

func (j RegexpMatcher) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

func (RegexpMatcher) MarshalText

func (j RegexpMatcher) MarshalText() ([]byte, error)

MarshalText implements the encoding.TextMarshaler interface.

func (*RegexpMatcher) Match

func (j *RegexpMatcher) Match(b []byte) bool

Match reports whether the byte slice b contains any match of the regular expression re.

func (*RegexpMatcher) MatchString

func (j *RegexpMatcher) MatchString(s string) bool

MatchString reports whether the string s contains any match of the regular expression re.

func (RegexpMatcher) String

func (j RegexpMatcher) String() string

String implements the fmt.Stringer interface.

func (*RegexpMatcher) UnmarshalJSON

func (j *RegexpMatcher) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler.

func (*RegexpMatcher) UnmarshalText

func (j *RegexpMatcher) UnmarshalText(bs []byte) error

UnmarshalText implements encoding.TextUnmarshaler by compiling the encoded value with regexp.Compile when treating it as a regular expression.

type Slug

type Slug string

Slug represents a url-encoded string that allows alphabet, digits, hyphens and underscores only.

func NewSlug

func NewSlug(value string) Slug

NewSlug creates a new slug instance from string.

func (Slug) String

func (s Slug) String() string

String implements the fmt.Stringer interface.

func (*Slug) UnmarshalJSON

func (s *Slug) UnmarshalJSON(bytes []byte) error

UnmarshalJSON implements the json.Unmarshaler interface.

func (*Slug) UnmarshalText

func (s *Slug) UnmarshalText(bs []byte) error

UnmarshalText implements encoding.TextUnmarshaler by parsing the provided text into a Slug and validating that it contains only allowed characters.

func (Slug) Validate

func (s Slug) Validate() error

Validate checks if the slug is valid.

type Time

type Time time.Time //nolint:recvcheck

Time wraps time.Time. It is used to parse and format custom date/time strings from YAML, JSON, and text formats.

func Date

func Date(
	year int,
	month time.Month,
	day int,
	hour int,
	minutes int,
	sec int,
	nsec int,
	loc *time.Location,
) Time

Date returns the Time corresponding to yyyy-mm-dd hh:mm:ss + nsec nanoseconds in the appropriate zone for that time in the given location. The month, day, hour, min, sec, and nsec values may be outside their usual ranges and will be normalized during the conversion. For example, October 32 converts to November 1. A daylight savings time transition skips or repeats times. For example, in the United States, March 13, 2011 2:15am never occurred, while November 6, 2011 1:15am occurred twice. In such cases, the choice of time zone, and therefore the time, is not well-defined. Date returns a time that is correct in one of the two zones involved in the transition, but it does not guarantee which. Date panics if loc is nil.

func Now

func Now() Time

Now returns the current local time.

func ParseDateTime

func ParseDateTime[B []byte | string](input B) (Time, error)

ParseDateTime parses date time in RFC 3339 or ISO 8601 format formats.

func Unix

func Unix(sec int64, nsec int64) Time

Unix returns the local Time corresponding to the given Unix time, sec seconds and nsec nanoseconds since January 1, 1970 UTC. It is valid to pass nsec outside the range [0, 999999999]. Not all sec values have a corresponding time value. One such value is 1<<63-1 (the largest int64 value).

func (Time) Add

func (t Time) Add(d time.Duration) Time

Add returns the time t+d.

func (Time) AddDate

func (t Time) AddDate(years int, months int, days int) Time

AddDate returns the time corresponding to adding the given number of years, months, and days to t. For example, AddDate(-1, 2, 3) applied to January 1, 2011 returns March 4, 2010.

Note that dates are fundamentally coupled to timezones, and calendrical periods like days don't have fixed durations. AddDate uses the Location of the Time value to determine these durations. That means that the same AddDate arguments can produce a different shift in absolute time depending on the base Time value and its Location. For example, AddDate(0, 0, 1) applied to 12:00 on March 27 always returns 12:00 on March 28. At some locations and in some years this is a 24 hour shift. In others it's a 23 hour shift due to daylight savings time transitions.

AddDate normalizes its result in the same way that Date does, so, for example, adding one month to October 31 yields December 1, the normalized form for November 31.

func (Time) After

func (t Time) After(u Time) bool

After reports whether the time instant t is after u.

func (Time) AppendBinary

func (t Time) AppendBinary(b []byte) ([]byte, error)

AppendBinary implements the encoding.BinaryAppender interface.

func (Time) AppendFormat

func (t Time) AppendFormat(b []byte, layout string) []byte

AppendFormat is like Time.Format but appends the textual representation to b and returns the extended buffer.

func (Time) AppendText

func (t Time) AppendText(b []byte) ([]byte, error)

AppendText implements the encoding.TextAppender interface. The time is formatted in RFC 3339 format with sub-second precision. If the timestamp cannot be represented as valid RFC 3339 (e.g., the year is out of range), then an error is returned.

func (Time) Before

func (t Time) Before(u Time) bool

Before reports whether the time instant t is before u.

func (Time) Clock

func (t Time) Clock() (int, int, int)

Clock returns the hour, minute, and second within the day specified by t.

func (Time) Compare

func (t Time) Compare(u Time) int

Compare compares the time instant t with u. If t is before u, it returns -1; if t is after u, it returns +1; if they're the same, it returns 0.

func (Time) Date

func (t Time) Date() (int, time.Month, int)

Date returns the year, month, and day in which t occurs.

func (Time) Day

func (t Time) Day() int

Day returns the day of the month specified by t.

func (Time) Equal

func (t Time) Equal(u Time) bool

Equal reports whether t and u represent the same time instant. Two times can be equal even if they are in different locations. For example, 6:00 +0200 and 4:00 UTC are Equal. See the documentation on the Time type for the pitfalls of using == with Time values; most code should use Equal instead.

func (Time) Format

func (t Time) Format(layout string) string

Format returns a textual representation of the time value formatted according to the layout defined by the argument. See the documentation for the constant called [Layout] to see how to represent the layout format. The executable example for Time.Format demonstrates the working of the layout string in detail and is a good reference.

func (Time) GoString

func (t Time) GoString() string

GoString implements fmt.GoStringer and formats t to be printed in Go source code.

func (*Time) GobDecode

func (t *Time) GobDecode(data []byte) error

GobDecode implements the gob.GobDecoder interface.

func (Time) GobEncode

func (t Time) GobEncode() ([]byte, error)

GobEncode implements the gob.GobEncoder interface.

func (Time) Hour

func (t Time) Hour() int

Hour returns the hour within the day specified by t, in the range [0, 23].

func (Time) ISOWeek

func (t Time) ISOWeek() (int, int)

ISOWeek returns the ISO 8601 year and week number in which t occurs. Week ranges from 1 to 53. Jan 01 to Jan 03 of year n might belong to week 52 or 53 of year n-1, and Dec 29 to Dec 31 might belong to week 1 of year n+1.

func (Time) In

func (t Time) In(loc *time.Location) Time

In returns a copy of t representing the same time instant, but with the copy's location information set to loc for display purposes.

func (Time) IsDST

func (t Time) IsDST() bool

IsDST reports whether the time in the configured location is in Daylight Savings Time.

func (Time) IsZero

func (t Time) IsZero() bool

IsZero reports whether t represents the zero time instant, January 1, year 1, 00:00:00 UTC.

func (Time) Local

func (t Time) Local() Time

Local returns t with the location set to local time.

func (Time) Location

func (t Time) Location() *time.Location

Location returns the time zone information associated with t.

func (Time) MarshalBinary

func (t Time) MarshalBinary() ([]byte, error)

MarshalBinary implements the encoding.BinaryMarshaler interface.

func (Time) MarshalJSON

func (t Time) MarshalJSON() ([]byte, error)

MarshalJSON implements the encoding/json.Marshaler interface. The time is a quoted string in the RFC 3339 format with sub-second precision. If the timestamp cannot be represented as valid RFC 3339 (e.g., the year is out of range), then an error is reported.

func (Time) MarshalText

func (t Time) MarshalText() ([]byte, error)

MarshalText implements the encoding.TextMarshaler interface. The output matches that of calling the Time.AppendText method.

func (Time) Minute

func (t Time) Minute() int

Minute returns the minute offset within the hour specified by t, in the range [0, 59].

func (Time) Month

func (t Time) Month() time.Month

Month returns the month of the year specified by t.

func (Time) Nanosecond

func (t Time) Nanosecond() int

Nanosecond returns the nanosecond offset within the second specified by t, in the range [0, 999999999].

func (Time) Round

func (t Time) Round(d time.Duration) Time

Round returns the result of rounding t to the nearest multiple of d (since the zero time). The rounding behavior for halfway values is to round up. If d <= 0, Round returns t stripped of any monotonic clock reading but otherwise unchanged. Round operates on the time as an absolute duration since the zero time; it does not operate on the presentation form of the time. Thus, Round(Hour) may return a time with a non-zero minute, depending on the time's Location.

func (Time) Second

func (t Time) Second() int

Second returns the second offset within the minute specified by t, in the range [0, 59].

func (Time) String

func (t Time) String() string

String returns the time formatted using the format string

"2006-01-02 15:04:05.999999999 -0700 MST" If the time has a monotonic clock reading, the returned string includes a final field "m=±<value>", where value is the monotonic clock reading formatted as a decimal number of seconds.

The returned string is meant for debugging; for a stable serialized representation, use t.MarshalText, t.MarshalBinary, or t.Format with an explicit format string.

func (Time) Sub

func (t Time) Sub(u Time) time.Duration

Sub returns the duration t-u. If the result exceeds the maximum (or minimum) value that can be stored in a time.Duration, the maximum (or minimum) duration will be returned. To compute t-d for a duration d, use t.Add(-d).

func (Time) Truncate

func (t Time) Truncate(d time.Duration) Time

Truncate returns the result of rounding t down to a multiple of d (since the zero time). If d <= 0, Truncate returns t stripped of any monotonic clock reading but otherwise unchanged. Truncate operates on the time as an absolute duration since the zero time; it does not operate on the presentation form of the time. Thus, Truncate(Hour) may return a time with a non-zero minute, depending on the time's Location.

func (Time) UTC

func (t Time) UTC() Time

UTC returns t with the location set to UTC.

func (Time) Unix

func (t Time) Unix() int64

Unix returns t as a Unix time, the number of seconds elapsed since January 1, 1970 UTC. The result does not depend on the location associated with t. Unix-like operating systems often record time as a 32-bit count of seconds, but since the method here returns a 64-bit value it is valid for billions of years into the past or future.

func (Time) UnixMicro

func (t Time) UnixMicro() int64

UnixMicro returns t as a Unix time, the number of microseconds elapsed since January 1, 1970 UTC. The result is undefined if the Unix time in microseconds cannot be represented by an int64 (a date before year -290307 or after year 294246). The result does not depend on the location associated with t.

func (Time) UnixMilli

func (t Time) UnixMilli() int64

UnixMilli returns t as a Unix time, the number of milliseconds elapsed since January 1, 1970 UTC. The result is undefined if the Unix time in milliseconds cannot be represented by an int64 (a date more than 292 million years before or after 1970). The result does not depend on the location associated with t.

func (Time) UnixNano

func (t Time) UnixNano() int64

UnixNano returns t as a Unix time, the number of nanoseconds elapsed since January 1, 1970 UTC. The result is undefined if the Unix time in nanoseconds cannot be represented by an int64 (a date before the year 1678 or after 2262). Note that this means the result of calling UnixNano on the zero Time is undefined. The result does not depend on the location associated with t.

func (*Time) UnmarshalBinary

func (t *Time) UnmarshalBinary(data []byte) error

UnmarshalBinary implements the encoding.BinaryUnmarshaler interface.

func (*Time) UnmarshalJSON

func (t *Time) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the encoding/json.Unmarshaler interface. The time must be a quoted string in the RFC 3339 or ISO 8601 format.

func (*Time) UnmarshalText

func (t *Time) UnmarshalText(data []byte) error

UnmarshalText implements the encoding.TextUnmarshaler interface. The time must be in the RFC 3339 or ISO 8601 format.

func (Time) Weekday

func (t Time) Weekday() time.Weekday

Weekday returns the day of the week specified by t.

func (Time) Year

func (t Time) Year() int

Year returns the year in which t occurs.

func (Time) YearDay

func (t Time) YearDay() int

YearDay returns the day of the year specified by t, in the range [1,365] for non-leap years, and [1,366] in leap years.

func (Time) Zone

func (t Time) Zone() (string, int)

Zone computes the time zone in effect at time t, returning the abbreviated name of the zone (such as "CET") and its offset in seconds east of UTC.

func (Time) ZoneBounds

func (t Time) ZoneBounds() (Time, Time)

ZoneBounds returns the bounds of the time zone in effect at time t. The zone begins at start and the next zone begins at end. If the zone begins at the beginning of time, start will be returned as a zero Time. If the zone goes on forever, end will be returned as a zero Time. The Location of the returned times will be the same as t.

type ValidateHTTPURLOptions

type ValidateHTTPURLOptions struct {
	AllowedSchemes  []string
	AllowedHosts    []string
	BlockedHosts    []string
	PublicIPOnly    bool
	AllowedIPRanges []string
	BlockedIPRanges []string
	// Custom lookup IP function.
	LookupIP func(ctx context.Context, host string) ([]net.IP, error)
}

ValidateHTTPURLOptions represent URL validation options.

type ValidateIPOptions

type ValidateIPOptions struct {
	// Block all private IPs.
	PublicIPOnly bool
	// IP ranges to allow.
	AllowedIPRanges []*net.IPNet
	// IP ranges to block.
	BlockedIPRanges []*net.IPNet
	// Custom lookup IP function.
	LookupIP func(ctx context.Context, host string) ([]net.IP, error)
}

ValidateIPOptions represent URL validation options.

type Wildcard

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

Wildcard represents a string with a wildcard pattern.

func NewWildcard

func NewWildcard(input string) (Wildcard, bool)

NewWildcard creates a new Wildcard instance from string.

func (Wildcard) Equal

func (w Wildcard) Equal(target Wildcard) bool

Equal checks if the target value is equal.

func (Wildcard) IsZero

func (w Wildcard) IsZero() bool

IsZero returns true if the current instance is in its zero state (both prefix and suffix are empty).

func (Wildcard) Match

func (w Wildcard) Match(s string) bool

Match checks if the input string matches the wildcard pattern.

func (Wildcard) String

func (w Wildcard) String() string

String implements the fmt.Stringer interface.

Directories

Path Synopsis
Package httperror defines HTTP error types.
Package httperror defines HTTP error types.
Package httpheader defines HTTP header constants.
Package httpheader defines HTTP header constants.

Jump to

Keyboard shortcuts

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