goutils

package module
v0.0.0-...-5f54e4d Latest Latest
Warning

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

Go to latest
Published: Jan 15, 2026 License: Apache-2.0 Imports: 20 Imported by: 0

README

goutils

goutils includes common functions for other Go packages.

Documentation

Overview

Package goutils includes common functions for other Go packages.

Copyright 2025 The RelyChan Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Index

Constants

This section is empty.

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 (
	// ErrInvalidHTTPScheme represents an invalid http(s) scheme error.
	ErrInvalidHTTPScheme = errors.New("invalid http(s) scheme")
	// 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")
)

Functions

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 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) (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 GetAny

func GetAny(object map[string]any, key string) (any, bool)

GetAny get an unknown value from object by key.

func IsDigit

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

IsDigit checks if the character is a digit.

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 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 ParseRelativeOrHTTPURL

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

ParseRelativeOrHTTPURL validates and parses relative or HTTP URL.

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 ReadJSONOrYAMLFile

func ReadJSONOrYAMLFile[T any](ctx context.Context, filePath string) (*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 ToAnySlice

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

ToAnySlice converts the a typed slice to any slice.

func ToDebugString

func ToDebugString(value any, emptyValue string) string

ToDebugString returns a string representation of an arbitrary value for debugging or logging purposes. It wraps ToString, and if ToString returns an error, it falls back to fmt.Sprint to ensure a string is always returned. This function never returns an error; it always returns a string. The emptyValue parameter specifies the string to use if the input value is nil or otherwise empty.

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 ToPtr

func ToPtr[T any](value T) *T

ToPtr converts the a typed value to its pointer.

func ToString

func ToString(value any, emptyValue string) (string, error)

ToString converts an arbitrary value to its string representation.

It handles the following cases:

  • For nil values, it returns the provided emptyValue.
  • 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 emptyValue if nil.
  • For unsupported types, it attempts to marshal the value to JSON.

If JSON marshaling fails, it returns an error.

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

func ToStringWithCustomTypeFormatter

func ToStringWithCustomTypeFormatter(
	value any,
	emptyValue string,
	customTypeFormatter func(any) (string, error),
) (string, error)

ToStringWithCustomTypeFormatter converts an arbitrary value to its string representation.

It handles the following cases:

  • For nil values, it returns the provided emptyValue.
  • 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 emptyValue if nil.
  • For unsupported types, it invokes the customTypeFormatter function to format the value.

If the customTypeFormatter returns an error, it returns an error.

The emptyValue 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.

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) 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 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) MarshalYAML

func (d Duration) MarshalYAML() (any, error)

MarshalYAML implements the yaml.Marshaler 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.

func (*Duration) UnmarshalYAML

func (d *Duration) UnmarshalYAML(value *yaml.Node) error

UnmarshalYAML implements the yaml.Unmarshaler 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 ErrorDetail

type ErrorDetail struct {
	// A granular description on the specific error related to a body property, query parameter, path parameters, and/or header.
	Detail string `json:"detail"`
	// A JSON Pointer to a specific request body property that is the source of error.
	Pointer string `json:"pointer,omitempty"`
	// The name of the query or path parameter that is the source of error.
	Parameter string `json:"parameter,omitempty"`
	// The name of the header that is the source of error.
	Header string `json:"header,omitempty"`
	// A string containing additional provider specific codes to identify the error context.
	Code string `json:"code,omitempty"`
}

ErrorDetail is an object to provide explicit details on a problem towards an API consumer.

type IsZeroer

type IsZeroer interface {
	IsZero() bool
}

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

type RFC9457Error

type RFC9457Error struct {
	// A URI reference that identifies the problem type.
	Type string `json:"type,omitempty"`
	// The HTTP status code generated by the origin server for this occurrence of the problem.
	Status int `json:"status,omitempty"`
	// A short, human-readable summary of the problem type.
	Title string `json:"title,omitempty"`
	// A human-readable explanation specific to this occurrence of the problem.
	Detail string `json:"detail,omitempty"`
	// A URI reference that identifies the specific occurrence of the problem.
	// It may or may not yield further information if dereferenced.
	Instance string `json:"instance,omitempty"`
	// An API specific error code aiding the provider team understand the error based on their own potential taxonomy or registry.
	Code string `json:"code,omitempty"`
	// An array of error details to accompany a problem details response.
	Errors []ErrorDetail `json:"errors,omitempty"`
}

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

func NewAlreadyExistsError

func NewAlreadyExistsError(errors ...ErrorDetail) RFC9457Error

NewAlreadyExistsError creates an error that occurs when the resource being created is found to already exist on the server.

func NewBadRequestError

func NewBadRequestError(errors ...ErrorDetail) RFC9457Error

NewBadRequestError creates an error that occurs when the server cannot or will not process the request due to something that is perceived to be a client error (for example, malformed request syntax, invalid request message framing, or deceptive request routing). Your client application initiated a request that is malformed. Please review your client request against the defined semantics for the API.

func NewBusinessRuleViolationError

func NewBusinessRuleViolationError(errors ...ErrorDetail) RFC9457Error

NewBusinessRuleViolationError occurs when the request is deemed unprocessable. Your client issued a request that failed business rule validation. Please review your request to determine if you can remain within appropriate business rules. Consider validating your request against available metadata (e.g. schemas) prior to sending to the server.

func NewForbiddenError

func NewForbiddenError(errors ...ErrorDetail) RFC9457Error

NewForbiddenError creates an error that occurs when the requested resource (and/or operation combination) is not authorized for the requesting client (and or authorization context). Your client application tried to perform an operation on a resource that it’s not authorized to perform in the given context.

func NewInvalidBodyPropertyFormatError

func NewInvalidBodyPropertyFormatError(errors ...ErrorDetail) RFC9457Error

NewInvalidBodyPropertyFormatError occurs when the request body contains a malformed property.

func NewInvalidBodyPropertyValueError

func NewInvalidBodyPropertyValueError(errors ...ErrorDetail) RFC9457Error

NewInvalidBodyPropertyValueError occurs when the request body contains an invalid property value.

func NewInvalidRequestHeaderFormatError

func NewInvalidRequestHeaderFormatError(errors ...ErrorDetail) RFC9457Error

NewInvalidRequestHeaderFormatError occurs when the request contains a malformed request header. Your client issued a request that contained a malformed request header. Please review your request parameters and compare against the shared API definition when applicable. Consider validating your headers against the published schema or API definition metadata prior to sending to the server.

func NewInvalidRequestParameterFormatError

func NewInvalidRequestParameterFormatError(errors ...ErrorDetail) RFC9457Error

NewInvalidRequestParameterFormatError occurs when the request contains a malformed query or path parameter. Your client issued a request that contained a malformed query or path parameter. Please review your request parameters and compare against the shared API definition. Consider validating your parameters published schema prior to sending to the server.

func NewInvalidRequestParameterValueError

func NewInvalidRequestParameterValueError(errors ...ErrorDetail) RFC9457Error

NewInvalidRequestParameterValueError occurs when the request contains an invalid query or path parameter value.

func NewLicenseCancelledError

func NewLicenseCancelledError(errors ...ErrorDetail) RFC9457Error

NewLicenseCancelledError creates an error that occurs when the license associated with the client has been cancelled thus rendering the service unavailable.

func NewLicenseExpiredError

func NewLicenseExpiredError(errors ...ErrorDetail) RFC9457Error

NewLicenseExpiredError creates an error that occurs when the license associated with the client has expired thus rendering the service unavailable.

func NewMissingBodyPropertyError

func NewMissingBodyPropertyError(errors ...ErrorDetail) RFC9457Error

NewMissingBodyPropertyError creates a missing body property error. This problem occurs when the request sent to the API is missing an expected body property.

func NewMissingRequestHeaderError

func NewMissingRequestHeaderError(errors ...ErrorDetail) RFC9457Error

NewMissingRequestHeaderError occurs when the request sent to the API is missing an expected request header.

func NewMissingRequestParameterError

func NewMissingRequestParameterError(errors ...ErrorDetail) RFC9457Error

NewMissingRequestParameterError occurs when the request sent to the API is missing a query or path parameter.

func NewNotFoundError

func NewNotFoundError(errors ...ErrorDetail) RFC9457Error

NewNotFoundError creates an error that occurs when the requested resource could not be found. Your client application tried to access a resource that does not exist (or could not be found). Please review how your users initiated such a request.

func NewRFC9457Error

func NewRFC9457Error(httpStatus int, detail string) RFC9457Error

NewRFC9457Error creates an RFC9457Error instance with status.

func NewRFC9457ErrorFromResponse

func NewRFC9457ErrorFromResponse(resp *http.Response) RFC9457Error

NewRFC9457ErrorFromResponse creates an RFC9457Error from an HTTP response.

func NewServerError

func NewServerError(errors ...ErrorDetail) RFC9457Error

NewServerError creates an error that occurs when the server encounters an unexpected condition that prevents it from fulfilling the request. Your client application did everything correct. Unfortunately our API encountered a condition that resulted in this problem.

func NewServiceUnavailableError

func NewServiceUnavailableError(errors ...ErrorDetail) RFC9457Error

NewServiceUnavailableError creates an error that occurs when the service requested is currently unavailable and the server is not ready to handle the request. Your client application did everything correct. Unfortunately our API is currently unavailable.

func NewUnauthorizedError

func NewUnauthorizedError(errors ...ErrorDetail) RFC9457Error

NewUnauthorizedError creates an error that occurs when the request lacks valid authentication credentials. Your client application tried to access a resource without providing a valid access token or authentication information. Please ensure that your requests include the necessary authentication credentials.

func NewValidationError

func NewValidationError(errors ...ErrorDetail) RFC9457Error

NewValidationError occurs when the request is deemed unprocessable.

func (RFC9457Error) Error

func (e RFC9457Error) Error() string

Error implements the error interface for RFC9457Error.

type RFC9457ErrorWithExtensions

type RFC9457ErrorWithExtensions struct {
	RFC9457Error

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

RFC9457ErrorWithExtensions 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 NewRFC9457ErrorWithExtensions

func NewRFC9457ErrorWithExtensions(
	err RFC9457Error,
	extensions map[string]any,
) RFC9457ErrorWithExtensions

NewRFC9457ErrorWithExtensions creates a new RFC 9457 error with extensions.

func (RFC9457ErrorWithExtensions) MarshalJSON

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

MarshalJSON implements the json.Marshaler interface.

func (*RFC9457ErrorWithExtensions) UnmarshalJSON

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

UnmarshalJSON implements the json.Unmarshaler interface.

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) MarshalYAML

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

MarshalYAML implements the custom behavior for the yaml.Marshaler 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.

func (*RegexpMatcher) UnmarshalYAML

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

UnmarshalYAML implements custom deserialization for the yaml.Unmarshaler interface.

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) UnmarshalYAML

func (s *Slug) UnmarshalYAML(value *yaml.Node) error

UnmarshalYAML implements the yaml.Unmarshaler interface to decode value.

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) MarshalYAML

func (t Time) MarshalYAML() (any, error)

MarshalYAML implements the yaml.Marshaler interface.

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) UnmarshalYAML

func (t *Time) UnmarshalYAML(value *yaml.Node) error

UnmarshalYAML implements the yaml.Unmarshaler interface.

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