Documentation
¶
Index ¶
- Variables
- func AddPath(path, method string, s *openapi3.T, op *openapi3.Operation)
- func Date(layout string) *dateRule
- func DecodeAndValidate(r io.Reader, dst any) error
- func DecodeAndValidateContext(ctx context.Context, r io.Reader, dst any) error
- func DocBase(serviceName, description, version string) *openapi3.T
- func MissingRules(structPtr any, exclude ...string) []string
- func NewRequest(vs ...any) (*openapi3.RequestBodyRef, error)
- func NewRequestMust(vs ...any) *openapi3.RequestBodyRef
- func NewResponse(vs map[string]Response) (*openapi3.Responses, error)
- func NewResponseMust(vs map[string]Response) *openapi3.Responses
- func StructMulti(v any, fns ...func(any))
- func StructStringFunc(v any, f func(string) string)
- func StructToLower(v any)
- func StructTrimSpace(v any)
- func SwaggerHandler(prefix string, s *openapi3.T) (http.Handler, error)
- func SwaggerHandlerMust(prefix string, s *openapi3.T) http.Handler
- func UnmarshalAndValidate(b []byte, dst any) error
- func UnmarshalAndValidateCtx(ctx context.Context, b []byte, dst any) error
- func Validate(value any) error
- func ValidateCtx(ctx context.Context, value any) error
- func ValidateStruct(structPtr any, fields []*FieldRules) error
- func When(condition bool, desc string, rules ...Rule) *whenRule
- type ContextNormalizer
- type ContextRuler
- type FieldRules
- type Normalizer
- type Response
- type Rule
- func By(f RuleFunc, desc string) Rule
- func Custom(f func(any) error, desc string) Rule
- func Default(a any) Rule
- func Deprecate() Rule
- func Describe(desc string) Rule
- func Each(rules ...Rule) Rule
- func Example(ex any) Rule
- func HasAlphabetic() Rule
- func In(values ...any) Rule
- func KeyIn(values ...string) Rule
- func Length(lo, hi int) Rule
- func Max(threshold any) Rule
- func Min(threshold any) Rule
- func NewStringRule(validator func(string) bool, desc string) Rule
- func NewStringRuleDecimalMax(i uint) Rule
- func NewStringRuleWithError(validator func(string) bool, err validation.Error, desc string) Rule
- func NonCreditCardNumber() Rule
- func Skip(desc string) Rule
- func Unique(f func(a int) any, desc string) Rule
- type RuleFunc
- type Ruler
- type ValidationErrors
- type ValueRuler
Constants ¶
This section is empty.
Variables ¶
var Empty = absentRule{validation.Empty, true}
Empty checks if a not nil value is empty.
var Nil = absentRule{validation.Nil, false}
Nil is a validation rule that checks if a value is nil.
var NotNil = notNilRule{Rule: validation.NotNil}
NotNil is a validation rule that checks if a value is not nil.
var Required = requiredRule{ validation.Required, "required", }
Required is a validation rule that checks if a value is not empty.
Functions ¶
func Date ¶
func Date(layout string) *dateRule
Date creates a date validation rule with the given layout format. Use .Min() and .Max() to constrain the date range for documentation.
func DecodeAndValidateContext ¶
DecodeAndValidateContext is like DecodeAndValidate but passes a context to ContextNormalizer.Normalize and ContextRuler.Rules.
func MissingRules ¶
MissingRules returns the names of exported struct fields that have no corresponding rule in the Ruler's Rules(). Embedded Ruler fields are expanded and their inner fields checked recursively.
Automatically excluded:
- json:"-"
- docs:"skip"
- validate:"-" (field intentionally has no rules)
Use in tests to catch forgotten fields:
assert.Empty(t, v.MissingRules(&MyStruct{}))
assert.Empty(t, v.MissingRules(&MyStruct{}, "OptionalField"))
func NewRequest ¶
func NewRequest(vs ...any) (*openapi3.RequestBodyRef, error)
NewRequest generates an OpenAPI request body schema from the given value types.
func NewRequestMust ¶
func NewRequestMust(vs ...any) *openapi3.RequestBodyRef
NewRequestMust is like NewRequest but panics on error.
func NewResponse ¶
NewResponse creates an OpenAPI responses object. Map key is status code (e.g. "200", "4xx").
func NewResponseMust ¶
NewResponseMust is like NewResponse but panics on error. Map key is status code (e.g. "200", "4xx").
func StructMulti ¶
StructMulti runs all given functions on the struct pointer sequentially.
func StructStringFunc ¶
StructStringFunc applies f to every string field in the struct recursively.
func StructToLower ¶
func StructToLower(v any)
StructToLower runs strings.ToLower on all string fields in the struct recursively.
func StructTrimSpace ¶
func StructTrimSpace(v any)
StructTrimSpace runs strings.TrimSpace on all string fields in the struct recursively, including nested structs, pointer fields, slices, and map values.
func SwaggerHandler ¶
SwaggerHandler returns an http.Handler that serves the Swagger UI for the given OpenAPI spec. The prefix is stripped automatically, so just mount it:
http.Handle("/swagger/", apivalidation.SwaggerHandlerMust("/swagger/", spec))
func SwaggerHandlerMust ¶
SwaggerHandlerMust is like SwaggerHandler but panics on error.
func UnmarshalAndValidate ¶
UnmarshalAndValidate decodes JSON from r into dst, then validates. If dst implements Normalizer, recursively normalizes (top level first, then nested structs, slices, maps) before validation.
func UnmarshalAndValidateCtx ¶
UnmarshalAndValidateCtx is like UnmarshalAndValidate but passes a context to ContextNormalizer.Normalize and ContextRuler.Rules.
func Validate ¶
Validate is the single entry point for all validation. If value implements Ruler, validates struct fields via Rules(). If value implements ValueRuler, applies its rules to the value directly. Collection elements implementing Ruler are auto-validated.
func ValidateCtx ¶
ValidateCtx is like Validate but passes a context to ContextRuler.Rules().
func ValidateStruct ¶
func ValidateStruct(structPtr any, fields []*FieldRules) error
ValidateStruct validates a struct with explicit field rules. Prefer Validate for types implementing Ruler.
Types ¶
type ContextNormalizer ¶
ContextNormalizer is like Normalizer but receives a context. Called by UnmarshalAndValidateCtx before validation.
type ContextRuler ¶
type ContextRuler interface {
Rules(context.Context) []*FieldRules
}
ContextRuler is like Ruler but receives a context (for conditional rules).
type FieldRules ¶
type FieldRules struct {
// contains filtered or unexported fields
}
FieldRules binds a struct field pointer to its validation rules.
func Field ¶
func Field[T any](fieldPtr *T, rules ...Rule) *FieldRules
Field creates a FieldRules binding a struct field pointer to its validation rules.
type Normalizer ¶
type Normalizer interface {
Normalize()
}
Normalizer is implemented by types that need custom normalization after unmarshaling. Called by UnmarshalAndValidate before validation. When the top-level type implements Normalizer, normalization recurses into struct fields, slices, maps, and embedded structs, calling Normalize on any nested type that also implements it. Top level is always called first, then children depth-first.
type Response ¶
Response describes an HTTP response with a description and body types for schema generation.
type Rule ¶
type Rule interface {
Validate(value any) error
Describe(name string, schema *openapi3.Schema, ref *openapi3.SchemaRef) error
}
Rule is the interface that all validation rules must implement.
func Custom ¶
Custom returns a validation rule that uses f for validation and desc for documentation.
func Deprecate ¶
func Deprecate() Rule
Deprecate returns a documentation-only rule that marks the field as deprecated in the schema.
func Describe ¶
Describe returns a documentation-only rule that appends desc to the schema description.
func Each ¶
Each returns a validation rule that applies the given rules to each element of a slice or array.
func HasAlphabetic ¶
func HasAlphabetic() Rule
HasAlphabetic returns a validation rule that checks if a string contains at least one alphabetic character.
func Length ¶
Length returns a validation rule that checks if a string's rune length is within the specified range.
func Max ¶
Max returns a validation rule that checks if a value is less than or equal to the specified maximum.
func Min ¶
Min returns a validation rule that checks if a value is greater than or equal to the specified minimum.
func NewStringRule ¶
NewStringRule returns a string validation rule using desc as both the error message and schema description.
func NewStringRuleDecimalMax ¶
NewStringRuleDecimalMax returns a validation rule that limits the number of decimal places in a numeric string.
func NewStringRuleWithError ¶
NewStringRuleWithError returns a string validation rule with a custom error and schema description.
func NonCreditCardNumber ¶
func NonCreditCardNumber() Rule
NonCreditCardNumber returns a validation rule that rejects strings that look like credit card numbers.
type Ruler ¶
type Ruler interface {
Rules() []*FieldRules
}
Ruler is implemented by types that define validation rules for their fields. Use a pointer receiver so field pointers are stable:
func (s *MyStruct) Rules() []*FieldRules {
return []*FieldRules{Field(&s.Name, Required)}
}
type ValidationErrors ¶
type ValidationErrors = validation.Errors
type ValueRuler ¶
type ValueRuler interface {
ValueRules() []Rule
}
ValueRuler is implemented by non-struct types (e.g. type PaymentMethod string) that carry their own validation rules. The returned rules are automatically applied during both validation and OpenAPI schema generation wherever the type appears as a struct field.
type PaymentMethod string
const (
PaymentACH PaymentMethod = "ach"
PaymentCC PaymentMethod = "cc"
)
func (p PaymentMethod) ValueRules() []Rule {
return []Rule{In(PaymentACH, PaymentCC)}
}