runtime

package
v3.63.5 Latest Latest
Warning

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

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

Documentation

Index

Constants

View Source
const DateFormat = "2006-01-02"

Variables

View Source
var (
	ErrValidationEmail         = errors.New("email: failed to pass regex validation")
	ErrFailedToUnmarshalAsAOrB = errors.New("failed to unmarshal as either A or B")
	ErrMustBeMap               = errors.New("value must be map[string]any")
)

ErrValidationEmail is the sentinel error returned when an email fails validation

Functions

func AsMap

func AsMap[V any](v any) (map[string]V, error)

AsMap converts any value to a map[string]V by marshaling to JSON and unmarshaling back. This is useful for converting structured types to maps for query params, path params, and headers. Returns nil if the input is nil.

func CoalesceOrMerge

func CoalesceOrMerge(parts ...json.RawMessage) (json.RawMessage, error)

CoalesceOrMerge implements generic wrapper semantics: - 0 non-null parts -> "null" - 1 non-null part -> that value as-is (object/array/scalar) - many, all objects -> merged object (last wins) - many, all arrays -> concatenated array - otherwise -> error (ambiguous)

func ConvertFormFields

func ConvertFormFields(resp []byte) ([]byte, error)

ConvertFormFields converts a raw form-encoded response body to JSON format. It parses the form-encoded data, converts it to a map, and then marshals it to JSON.

func ConvertValidatorError

func ConvertValidatorError(err error) error

ConvertValidatorError converts a validator.ValidationErrors to our ValidationErrors type. This provides a consistent error format across all validation errors.

func EncodeFormFields

func EncodeFormFields(data any, encoding map[string]FieldEncoding) (string, error)

EncodeFormFields encodes the given data into a URL-encoded form string.

func EncodeQueryFields

func EncodeQueryFields(data any, encoding map[string]QueryEncoding) (string, error)

EncodeQueryFields builds a query string for query params per OAS 3.1 style matrix.

Arrays (name=expand, vals=[a,b]): - form, explode=true => expand=a&expand=b - form, explode=false => expand=a,b - spaceDelimited => expand=a%20b - pipeDelimited => expand=a%7Cb - deepObject (custom) => expand%5B%5D=a&expand%5B%5D=b

Objects (name=color, vals={R:100,G:200,B:150}): - form, explode=true => R=100&G=200&B=150 - form, explode=false => color=R,100,G,200,B,150 - spaceDelimited => color=R%20100%20G%20200%20B%20150 - pipeDelimited => color=R%7C100%7CG%7C200%7CB%7C150 - deepObject (spec) => color%5BR%5D=100&color%5BG%5D=200&color%5BB%5D=150

Scalars (name=x, val=v): always x=v (style choice irrelevant).

func JSONMerge

func JSONMerge(data, patch json.RawMessage) (json.RawMessage, error)

JSONMerge merges two JSON representation into a single object. `data` is the existing representation and `patch` is the new data to be merged in

func MarshalJSON

func MarshalJSON(v any) (json.RawMessage, error)

MarshalJSON marshals value respecting json.Marshaler.

func MaskSensitivePointer

func MaskSensitivePointer[T any](value *T, config SensitiveDataConfig) any

MaskSensitivePointer masks a pointer value

func MaskSensitiveString

func MaskSensitiveString(value string, config SensitiveDataConfig) string

MaskSensitiveString is a convenience function for masking string values

func MaskSensitiveValue

func MaskSensitiveValue(value any, config SensitiveDataConfig) any

MaskSensitiveValue masks a sensitive value based on the masking strategy

func NewClientAPIError

func NewClientAPIError(err error, opts ...ClientAPIErrorOption) error

NewClientAPIError creates a new ClientAPIError from the given error.

func NewValidationErrorFromError

func NewValidationErrorFromError(field string, err error) error

NewValidationErrorFromError creates ValidationErrors from a single error with a field prefix. This is a convenience wrapper around NewValidationErrorsFromErrors for a single error.

func Ptr

func Ptr[T any](v T) *T

Ptr returns a pointer to the given value. This is useful for creating pointers to constants or literals.

func RegisterCustomTypeFunc

func RegisterCustomTypeFunc(v *validator.Validate)

RegisterCustomTypeFunc registers a custom type function with the validator to extract values from types that have a Value() interface{} method. This is useful for union types (like Either) where only the active variant should be validated instead of all possible variants.

The function looks for any struct with a Value() method matching the signature:

func Value() interface{}

When found, it calls Value() and returns the result for validation instead of validating the struct's fields directly.

Note: The struct fields should also have `validate:"-"` tags to prevent the validator from validating them directly. This function only affects validation when using validator.Var() on the struct itself.

func UnmarshalJSON

func UnmarshalJSON(data []byte, v any) error

UnmarshalJSON unmarshals data into v, respecting custom Unmarshaler.

Types

type APIClient

type APIClient interface {
	GetBaseURL() string
	CreateRequest(ctx context.Context, params RequestOptionsParameters, reqEditors ...RequestEditorFn) (*http.Request, error)
	ExecuteRequest(ctx context.Context, req *http.Request, operationPath string) (*Response, error)
}

type APIClientOption

type APIClientOption func(*Client) error

APIClientOption allows setting custom parameters during construction.

func WithHTTPClient

func WithHTTPClient(doer HttpRequestDoer) APIClientOption

WithHTTPClient allows overriding the default Doer, which is automatically created using http.Client.

func WithRequestEditorFn

func WithRequestEditorFn(fn RequestEditorFn) APIClientOption

WithRequestEditorFn allows setting up a callback function, which will be called right before sending the request. This can be used to mutate the request.

type Client

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

Client is a client for making API requests. BaseURL is the base URL for the API. httpClient is the HTTP client to use for making requests. requestEditors is a list of callbacks for modifying requests which are generated before sending over the network.

func NewAPIClient

func NewAPIClient(baseURL string, opts ...APIClientOption) (*Client, error)

NewAPIClient creates a new client, with reasonable defaults.

func (*Client) CreateRequest

func (c *Client) CreateRequest(ctx context.Context, params RequestOptionsParameters, reqEditors ...RequestEditorFn) (*http.Request, error)

CreateRequest creates a new HTTP request with the given parameters and applies any request editors. It returns the created request or an error if the request could not be created.

func (*Client) ExecuteRequest

func (c *Client) ExecuteRequest(ctx context.Context, req *http.Request, operationPath string) (*Response, error)

ExecuteRequest sends the HTTP request and returns the response. It records the HTTP call with latency if an HTTPCallRecorder is set.

func (*Client) GetBaseURL

func (c *Client) GetBaseURL() string

GetBaseURL returns the base URL of the API client.

type ClientAPIError

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

ClientAPIError represents type for client API errors.

func (*ClientAPIError) Error

func (e *ClientAPIError) Error() string

Error implements the error interface.

func (*ClientAPIError) StatusCode

func (e *ClientAPIError) StatusCode() int

func (*ClientAPIError) Unwrap

func (e *ClientAPIError) Unwrap() error

Unwrap returns the underlying error.

type ClientAPIErrorOption

type ClientAPIErrorOption func(*ClientAPIError)

func WithStatusCode

func WithStatusCode(code int) ClientAPIErrorOption

type Date

type Date struct {
	time.Time
}

func (Date) MarshalJSON

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

func (Date) String

func (d Date) String() string

func (*Date) UnmarshalJSON

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

func (*Date) UnmarshalText

func (d *Date) UnmarshalText(data []byte) error

type Either

type Either[A, B any] struct {
	A A `validate:"-"`
	B B `validate:"-"`

	N int
}

func NewEitherFromA

func NewEitherFromA[A any, B any](a A) Either[A, B]

func NewEitherFromB

func NewEitherFromB[A any, B any](b B) Either[A, B]

func (*Either[A, B]) IsA

func (t *Either[A, B]) IsA() bool

func (*Either[A, B]) IsB

func (t *Either[A, B]) IsB() bool

func (Either[A, B]) MarshalJSON

func (t Either[A, B]) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler interface

func (*Either[A, B]) UnmarshalJSON

func (t *Either[A, B]) UnmarshalJSON(data []byte) error

func (*Either[A, B]) Validate

func (t *Either[A, B]) Validate() error

func (*Either[A, B]) Value

func (t *Either[A, B]) Value() any

type Email

type Email string

Email represents an email address. It is a string type that must pass regex validation before being marshalled to JSON or unmarshalled from JSON.

func (Email) MarshalJSON

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

func (*Email) UnmarshalJSON

func (e *Email) UnmarshalJSON(data []byte) error

type FieldEncoding

type FieldEncoding struct {
	Style       string
	Explode     *bool
	ContentType string
}

type File

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

func (*File) Bytes

func (file *File) Bytes() ([]byte, error)

func (File) FileSize

func (file File) FileSize() int64

func (File) Filename

func (file File) Filename() string

func (*File) InitFromBytes

func (file *File) InitFromBytes(data []byte, filename string)

func (*File) InitFromMultipart

func (file *File) InitFromMultipart(header *multipart.FileHeader)

func (File) MarshalJSON

func (file File) MarshalJSON() ([]byte, error)

func (File) Reader

func (file File) Reader() (io.ReadCloser, error)

func (*File) UnmarshalJSON

func (file *File) UnmarshalJSON(data []byte) error

type HttpRequestDoer

type HttpRequestDoer interface {
	Do(context context.Context, req *http.Request) (*http.Response, error)
}

type JSONNonZero

type JSONNonZero interface {
	JSONNonZero() bool
}

type Marshaler

type Marshaler interface {
	MarshalJSON() ([]byte, error)
}

type MaskType

type MaskType string

MaskType represents the type of masking to apply

const (
	MaskTypeFull    MaskType = "full"
	MaskTypeRegex   MaskType = "regex"
	MaskTypeHash    MaskType = "hash"
	MaskTypePartial MaskType = "partial"
)

Masking type constants

type Merger

type Merger struct {
	// Errors is slice of non-critical errors of merge operations
	Errors []error

	// Replaced is describe replacements
	// Key is path in document like
	//   "prop1.prop2.prop3" for object properties or
	//   "arr1.1.prop" for arrays
	// Value is value of replacement
	Replaced map[string]any

	// CopyNonexistent enables setting fields into the result
	// which only exist in the patch.
	CopyNonexistent bool
}

Merger describes result of merge operation and provides configuration.

func (*Merger) Merge

func (m *Merger) Merge(data, patch any) any

Merge merges patch document to data document

Returning merged document. Result of merge operation can be obtained from the Merger. Result information is discarded before merging.

func (*Merger) MergeBytes

func (m *Merger) MergeBytes(dataBuff, patchBuff []byte) ([]byte, error)

MergeBytes merges patch document buffer to data document buffer

Returning merged document buffer, merge info and error if any

func (*Merger) MergeBytesIndent

func (m *Merger) MergeBytesIndent(dataBuff, patchBuff []byte, prefix, indent string) ([]byte, error)

MergeBytesIndent merges patch document buffer to data document buffer

Use prefix and indent for set indentation like in json.MarshalIndent

Returning merged document buffer and error if any.

type QueryEncoding

type QueryEncoding struct {
	Style   string
	Explode *bool
}

type RequestEditorFn

type RequestEditorFn func(ctx context.Context, req *http.Request) error

RequestEditorFn is the function signature for the RequestEditor callback function

type RequestOptions

type RequestOptions interface {
	GetPathParams() (map[string]any, error)
	GetQuery() (map[string]any, error)
	GetBody() any
	GetHeader() (map[string]string, error)
}

type RequestOptionsParameters

type RequestOptionsParameters struct {
	Options       RequestOptions
	RequestURL    string
	Method        string
	ContentType   string
	BodyEncoding  map[string]FieldEncoding
	QueryEncoding map[string]QueryEncoding
}

RequestOptionsParameters holds the parameters for creating a request.

type Response

type Response struct {
	Content    []byte
	StatusCode int
	Headers    http.Header
	Raw        *http.Response
}

type SensitiveDataConfig

type SensitiveDataConfig struct {
	Type        MaskType // masking type: full, regex, hash, or partial
	Replacement string   // custom replacement string for "full" and "partial" masks (default: "********")
	Pattern     string   // regex pattern for "regex" type
	Algorithm   string   // hash algorithm for "hash" type (e.g., "sha256")
	KeepPrefix  int      // number of characters to keep at start for "partial" type
	KeepSuffix  int      // number of characters to keep at end for "partial" type
}

SensitiveDataConfig holds configuration for masking sensitive data

func NewDefaultSensitiveDataConfig

func NewDefaultSensitiveDataConfig() *SensitiveDataConfig

NewDefaultSensitiveDataConfig returns a SensitiveDataConfig with default settings (full masking)

func (*SensitiveDataConfig) EscapedPattern

func (s *SensitiveDataConfig) EscapedPattern() string

EscapedPattern returns the pattern with backslashes escaped for use in Go string literals

func (*SensitiveDataConfig) Mask

func (s *SensitiveDataConfig) Mask() string

Mask returns the Type as a string for template compatibility

func (*SensitiveDataConfig) Unmarshal

func (s *SensitiveDataConfig) Unmarshal(value any) error

Unmarshal parses the x-sensitive-data extension value from YAML/JSON Supports: - boolean: true -> full masking - string: "full", "hash", "regex", "partial" -> that masking type - object: detailed configuration with mask type and parameters

type Unmarshaler

type Unmarshaler interface {
	UnmarshalJSON([]byte) error
}

type ValidationError

type ValidationError struct {
	Field   string `json:"field"`
	Message string `json:"message"`

	// underlying error, not serialized
	Err error `json:"-"`
}

func NewValidationError

func NewValidationError(field, message string) ValidationError

func (ValidationError) Error

func (e ValidationError) Error() string

func (ValidationError) Unwrap

func (e ValidationError) Unwrap() error

Unwrap returns the underlying error for error wrapping support

type ValidationErrors

type ValidationErrors []ValidationError

func NewValidationErrorsFromError

func NewValidationErrorsFromError(err error) ValidationErrors

NewValidationErrorsFromError creates a new ValidationErrors from a single error.

func NewValidationErrorsFromErrors

func NewValidationErrorsFromErrors(prefix string, errs []error) ValidationErrors

NewValidationErrorsFromErrors creates a new ValidationErrors from a list of errors. If prefix is provided, it will be prepended to each field name with a dot.

func NewValidationErrorsFromString

func NewValidationErrorsFromString(field, message string) ValidationErrors

NewValidationErrorsFromString creates a new ValidationErrors from a field and message.

func (ValidationErrors) Add

func (ve ValidationErrors) Add(field, message string) ValidationErrors

Add adds a single ValidationError to the collection.

func (ValidationErrors) Append

func (ve ValidationErrors) Append(field string, err error) ValidationErrors

Append adds validation errors from the given error to the collection. It handles ValidationError, ValidationErrors, and other error types.

func (ValidationErrors) Error

func (ve ValidationErrors) Error() string

func (ValidationErrors) Unwrap

func (ve ValidationErrors) Unwrap() []error

type Validator

type Validator interface {
	Validate() error
}

Validator is an interface for types that can validate themselves.

Jump to

Keyboard shortcuts

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