forms

package
v0.0.0-...-e4af6d1 Latest Latest
Warning

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

Go to latest
Published: Aug 8, 2026 License: AGPL-3.0 Imports: 18 Imported by: 0

Documentation

Overview

Package forms provides helpers and functions to create and validate forms.

Introduction

Write some documentation.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrFormIsBound        = errors.New("form is already bound")
	ErrFormInvalidInput   = errors.New("invalid input data")
	ErrUnknownContentType = errors.New("unknown content type")
	ErrUnexpected         = Gettext("an unexpected error has occurred")
)

Error definitions.

View Source
var (
	// Gettext is an alias for newError (for locales extractor).
	Gettext = newError
	// Pgettext is an alias for newError (for locales extractor).
	Pgettext = newErrorCtx
)
View Source
var (
	ErrRequired     = Gettext("field is required")
	ErrInvalidEmail = Gettext("not a valid email address")
	ErrInvalidURL   = Gettext("invalid URL")

	// ErrSkipValidation is an error that is not returned and stop
	// any subsequent validator.
	ErrSkipValidation = errors.New("skip")
)

Error definitions.

View Source
var DiscardEmpty = CleanerFunc[[]string](func(v []string) []string {
	return slices.DeleteFunc(v, func(s string) bool {
		return s == ""
	})
})

DiscardEmpty is a ValueCleaner that removes empty values from a list of string.

View Source
var ErrInvalidValue = errors.New("invalid value")

ErrInvalidValue is the error for invalid value.

View Source
var IsEmail = TypedValidator(func(v string) bool {
	l := len(v)
	c := 0

	for i, x := range v {
		if x == '@' {
			if c > 0 {
				return false
			}
			if i == 0 {
				return false
			}
			if i == l-1 {
				return false
			}
			c++
		}

		if unicode.Is(unicode.C, x) || unicode.Is(unicode.Space, x) {
			return false
		}
	}

	return c == 1
}, ErrInvalidEmail)

IsEmail performs a rough check of the email address. That is, it only checks for the presence of "@", only once and in the string. Control characters and spaces are not allowed.

View Source
var RequestLoaders = map[string]func(r *http.Request, f FormBinder) error{

	string(MimeJSON): func(r *http.Request, f FormBinder) error {
		if err := json.NewDecoder(r.Body).Decode(f); err != nil {
			return ErrFormInvalidInput
		}
		return nil
	},

	string(MimeURLEncoded): func(r *http.Request, f FormBinder) error {
		if err := r.ParseForm(); err != nil {
			return ErrFormInvalidInput
		}
		if err := UnmarshalURLValues(r.Form, f); err != nil {
			return ErrFormInvalidInput
		}
		return nil
	},

	string(MimeMultipart): func(r *http.Request, f FormBinder) error {
		if err := unmarshalMultipart(r, f); err != nil {
			return ErrFormInvalidInput
		}
		return nil
	},
}

RequestLoaders contains the functions used to load a request's into a FormBinder.

Adding or removing items from RequestLoaders should only be done in a module's init function.

For example, if you need to support "text/json" as "application/json", you can add this in a module:

func init() {
	RequestLoaders["text/json"] = RequestLoaders[string(forms.MimeJSON)]
}
View Source
var Required = FieldValidatorFunc(func(f Binder) error {
	if !f.IsBound() || f.IsEmpty() || f.IsNil() {
		return FatalError(ErrRequired)
	}
	return nil
})

Required is a FieldValidator that returns an error when a field is null, not bound or empty.

View Source
var RequiredOrNil = FieldValidatorFunc(func(f Binder) error {
	if !f.IsNil() && f.IsEmpty() {
		return FatalError(ErrRequired)
	}
	return nil
})

RequiredOrNil is a FieldValidator that returns an error when the field is empty but not null.

View Source
var Skip = FieldValidatorFunc(func(f Binder) error {
	if f.IsNil() || f.IsEmpty() || f.String() == "" {
		return ErrSkipValidation
	}
	return nil
})

Skip skips subsequent validators when the field is null or empty.

View Source
var SplitLines = ValueValidatorFunc[[]string](func(f Binder, value []string) error {
	field, ok := f.(Setter[[]string])
	if !ok {
		return nil
	}

	res := []string{}
	for _, x := range value {
		for l := range strings.Lines(x) {
			if s := strings.TrimSpace(l); s != "" {
				res = append(res, s)
			}
		}
	}
	field.Set(res)
	return nil
})

SplitLines works on any []string value and populates the field after spliting each item's lines. It will trim spaces on each value.

Trim is a ValueCleaner that trims spaces on string values.

View Source
var ValidateTagName = "validate"

ValidateTagName is the struct field tag name used to declare validators. It can be changed in an init function if needed.

Functions

func ApplyCleaners

func ApplyCleaners[T any](p ValidatorsProvider, v T) T

ApplyCleaners applies the p's [ValueCleaner]s. It returns the cleaned up value.

func ApplyValidators

func ApplyValidators[T any](f Binder, v any, validators ...Validator) (errs []error)

ApplyValidators applies the given validators to the field and returns all found errors. It can run at any time, including during a form or field custom validation.

Every FieldValidator is applied. Every ValueValidator for T and is applied.

A validator that returns a FatalError or ErrSkipValidation will stops any further validation.

func Bind

func Bind(r *http.Request, f FormBinder)

Bind loads the data using the method tied to the request's content-type header.

func BindAs

func BindAs[T any](r *http.Request, options ...func(FormBinder)) *T

BindAs combines New and Bind in one step, returning the newly created form.

func BindValues

func BindValues(values url.Values, f FormBinder)

BindValues loads the data from a url.Values input. This can be used to load values only from the URL's query string.

func Choices

func Choices[T comparable](f Binder, choices ...ValueChoice[T])

Choices adds a list of ValueChoice to the field f. If it implements ChoicesProvider, the choice list is added to the field.

When it implements ValidatorProvider, a validator is added so only valid choices are accepted.

func DecodeValueData

func DecodeValueData[IN inputData, T any](
	v SetterValuer[T],
	data IN,
	unmarshal func(data IN) (res *T, err error),
) error

DecodeValueData is the function that decodes a value and sets its flags. It receives a SetterValuer an input ([]byte or []string) and a suitable unmarshal function.

When the unmarshal function returns nil without error, the value's flags are set to IsNil, IsEmpty, IsBound and [IsOk].

When the unmarshal function returns an ErrValueFlags error, the error is ignored and its flag is added to the existing ones.

func IterErrors

func IterErrors(err error) iter.Seq[error]

IterErrors returns an iterator over an error and flatens the result. It recursively yields errors contained in the error when it implements Unwrap() []error (like errors.Join or Errors do). Every result is wrapped in a [localizedError] so its call to Error() produces a translated error.

func IterErrorsTr

func IterErrorsTr(ctx context.Context, err error) iter.Seq[error]

IterErrorsTr returns an iterator that yields errors wrapped as localized error so they can be translated when calling their Error() method.

func MarshalValues

func MarshalValues(in any) map[string]any

MarshalValues returns a recursive map of all values implementing Binder. It panics when "in" is not a struct.

func New

func New[T any](ctx context.Context, options ...func(FormBinder)) *T

New prepares and returns a new instance of T. It panics if T is not a struct implementing FormBinder or when a field's "validate" tag does not exist.

func RegisterTaggedValidator

func RegisterTaggedValidator(fn TaggedValidatorFunc)

RegisterTaggedValidator adds a new TaggedValidatorFunc to the tagged validators registry. It can be called in an init function. Any tag added here will be global.

func UnmarshalURLValues

func UnmarshalURLValues(values url.Values, v any) (err error)

UnmarshalURLValues decode url.Values into v. v must be a pointer to a struct. Nested values are supported with a "." separator. For example, the following struct:

type nested {
	Name string `json:"string"`
	Meta struct {
		Address string `json:"address"`
	} `json:"meta"`
}

can be decoded with "?name=someone&meta.address=somewhere"

The output struct's fields support the "json" tag.

Each value name matching a struct field is decoded using UnmarshalValues while values with a prefix are sent again to this function with the prefix removed.

func UnmarshalValues

func UnmarshalValues(values []string, v any) (err error)

UnmarshalValues decodes a list of string into v. When v implements ValuesUnmarshaler, encoding.TextUnmarshaler or encoding.BinaryUnmarshaler, their respective unmarshal methods have priority (in that order).

Otherwise, scalar values are decoded (bool, string, float, signed and unsigned integer). With encoding.TextUnmarshaler, encoding.BinaryUnmarshaler or scalar values, only the first item from values is decoded.

When v is a slice, UnmarshalValues is called on each item in values.

func WithTranslator

func WithTranslator(ctx context.Context, tr Translator) context.Context

WithTranslator adds a Translator to the given context.Context.

func WrapTrError

func WrapTrError(ctx context.Context, err error) error

WrapTrError wraps a given error into a new l10n aware error.

Types

type BaseValue

type BaseValue[T any] struct {
	// contains filtered or unexported fields
}

BaseValue is an implementation of Valuer. It provides a working decoder and a generic fmt.Stringer without any specialization.

func (BaseValue[T]) Flags

func (v BaseValue[T]) Flags() ValueFlags

Flags returns the value's ValueFlags.

func (BaseValue[T]) IsBound

func (v BaseValue[T]) IsBound() bool

IsBound return true if the value was attached after decoding.

func (BaseValue[T]) IsEmpty

func (v BaseValue[T]) IsEmpty() bool

IsEmpty return true if the value is empty.

func (BaseValue[T]) IsNil

func (v BaseValue[T]) IsNil() bool

IsNil returns true if the input value was null.

func (BaseValue[T]) MarshalJSON

func (v BaseValue[T]) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

func (*BaseValue[T]) Set

func (v *BaseValue[T]) Set(in T)

Set sets the value's value.

func (*BaseValue[T]) SetFlags

func (v *BaseValue[T]) SetFlags(f ValueFlags)

SetFlags replaces the value's ValueFlags.

func (*BaseValue[T]) SetValidators

func (v *BaseValue[T]) SetValidators(validators []Validator)

SetValidators implements ValidatorsProvider and sets the value's validators.

func (BaseValue[T]) String

func (v BaseValue[T]) String() string

String returns a string representation of the value.

func (*BaseValue[T]) UnmarshalJSON

func (v *BaseValue[T]) UnmarshalJSON(in []byte) error

UnmarshalJSON implements json.Unmarshaler.

func (*BaseValue[T]) UnmarshalValues

func (v *BaseValue[T]) UnmarshalValues(values []string) error

UnmarshalValues implement ValuesUnmarshaler.

func (BaseValue[T]) Validators

func (v BaseValue[T]) Validators() []Validator

Validators implements ValidatorsProvider and returns the value's validators.

func (BaseValue[T]) Value

func (v BaseValue[T]) Value() T

Value returns the value's value.

type Binder

type Binder interface {
	fmt.Stringer
	IsBound() bool
	IsEmpty() bool
	IsNil() bool
	Errors() Errors
	V() any
}

Binder describes a type that is "bound" to some data by the means of appropriate unmarshaling. It then provides informations about its state.

type BooleanField

type BooleanField = Field[bool, BooleanValue]

BooleanField is a field that holds a [bool] value.

type BooleanValue

type BooleanValue struct {
	BaseValue[bool]
}

BooleanValue is a Valuer for [bool] types.

func (BooleanValue) String

func (v BooleanValue) String() string

func (*BooleanValue) UnmarshalValues

func (v *BooleanValue) UnmarshalValues(values []string) error

UnmarshalValues implements ValuesUnmarshaler. It parses a value "on" as true.

type ChoicesField

type ChoicesField[T comparable] struct {
	// contains filtered or unexported fields
}

ChoicesField implements ChoicesProvider. It can be used to augment a Field for comparable types.

func (*ChoicesField[T]) Choices

func (f *ChoicesField[T]) Choices() ValueChoices[T]

Choices returns the stored choices.

func (*ChoicesField[T]) SetChoices

func (f *ChoicesField[T]) SetChoices(choices ValueChoices[T])

SetChoices sets the stored choices.

type ChoicesProvider

type ChoicesProvider[T comparable] interface {
	Choices() ValueChoices[T]
	SetChoices(ValueChoices[T])
}

ChoicesProvider is an interface implemented by types than can store and return ValueChoices.

type CleanerFunc

type CleanerFunc[T any] func(v T) T

CleanerFunc is a ValueCleaner.

func (CleanerFunc[T]) Clean

func (c CleanerFunc[T]) Clean(v T) T

Clean implements ValueCleaner.

type ContextHolder

type ContextHolder interface {
	SetContext(context.Context)
}

ContextHolder is an interface implemented by types that can carry a context.Context.

type DatetimeField

type DatetimeField = Field[time.Time, DatetimeValue]

DatetimeField is a field that holds a time.Time value.

type DatetimeListField

type DatetimeListField = ListField[time.Time, ListValue[time.Time, DatetimeValue]]

DatetimeListField is a field that holds a list of time.Time values.

type DatetimeValue

type DatetimeValue struct {
	BaseValue[time.Time]
}

DatetimeValue is a Valuer for time.Time values. It can parse more formats than what's allowed by time.Time unmarshal functions.

func (DatetimeValue) String

func (v DatetimeValue) String() string

String returns the value formatted with time.RFC3339.

func (*DatetimeValue) UnmarshalJSON

func (v *DatetimeValue) UnmarshalJSON(in []byte) error

UnmarshalJSON implements json.Unmarshaler.

func (*DatetimeValue) UnmarshalValues

func (v *DatetimeValue) UnmarshalValues(values []string) error

UnmarshalValues implements ValuesUnmarshaler.

type ErrValueFlags

type ErrValueFlags ValueFlags

ErrValueFlags is an error that can be returned from DecodeValueData.

func (ErrValueFlags) Error

func (e ErrValueFlags) Error() string

type Errors

type Errors []error

Errors is an error list.

func FatalError

func FatalError(err error) Errors

FatalError is an error that has the effect to stop any subsequent validation.

func (Errors) Error

func (e Errors) Error() string

func (Errors) MarshalJSON

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

MarshalJSON implements json.Marshaler.

func (Errors) String

func (e Errors) String() string

func (Errors) Unwrap

func (e Errors) Unwrap() []error

type Field

type Field[T any, V Valuer[T]] struct {
	// contains filtered or unexported fields
}

Field is a generic field that holds a value of the given type and implements Binder. It's the common building block for a specialized field.

func (*Field[T, V]) AddErrors

func (f *Field[T, V]) AddErrors(errs ...error)

AddErrors add errors to the field.

func (*Field[T, V]) ApplyValidators

func (f *Field[T, V]) ApplyValidators(validators ...Validator)

ApplyValidators applies the given validators to the field and add the resulting errors to the field's error list. It can run at any time, including during a form or field custom validation.

func (Field[T, V]) Errors

func (f Field[T, V]) Errors() Errors

Errors return the field's Errors.

func (Field[T, V]) IsBound

func (f Field[T, V]) IsBound() bool

IsBound returns true if the field is bound.

func (Field[T, V]) IsEmpty

func (f Field[T, V]) IsEmpty() bool

IsEmpty returns true if the field's value is empty.

func (Field[T, V]) IsNil

func (f Field[T, V]) IsNil() bool

IsNil returns true if the field's value is null.

func (*Field[T, V]) IsValid

func (f *Field[T, V]) IsValid() bool

IsValid applies the field's FieldValidator and ValueValidator. Each returned error is added to the field's error list. It returns false when the error list is not empty.

func (Field[T, V]) MarshalJSON

func (f Field[T, V]) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

func (Field[T, V]) Name

func (f Field[T, V]) Name() string

Name returns the field's name.

func (*Field[T, V]) Set

func (f *Field[T, V]) Set(v T)

Set sets the Valuer's value if it implements Setter.

func (*Field[T, V]) SetContext

func (f *Field[T, V]) SetContext(ctx context.Context)

SetContext sets the field's context. It implements ContextHolder.

func (*Field[T, V]) SetName

func (f *Field[T, V]) SetName(name string)

SetName sets the field's name.

func (*Field[T, V]) SetNil

func (f *Field[T, V]) SetNil()

SetNil sets the Valuer to nil if it implements Setter and FlagSetter. It only sets the nil flag and doesn't empty the value.

func (*Field[T, V]) SetValidators

func (f *Field[T, V]) SetValidators(validators []Validator)

SetValidators implements ValidatorsProvider and sets the field's validators.

func (Field[T, V]) String

func (f Field[T, V]) String() string

String returns the field's Valuer string value.

func (*Field[T, V]) UnmarshalFiles

func (f *Field[T, V]) UnmarshalFiles(files []*multipart.FileHeader) error

UnmarshalFiles implements FilesUnmarshaler. It only works on [Valuer]s implementing FilesUnmarshaler themselves.

func (*Field[T, V]) UnmarshalJSON

func (f *Field[T, V]) UnmarshalJSON(in []byte) error

UnmarshalJSON implements json.Unmarshaler. It always returns nil and errors, if any, are added to the field's error list.

func (*Field[T, V]) UnmarshalValues

func (f *Field[T, V]) UnmarshalValues(values []string) error

UnmarshalValues implement ValuesUnmarshaler. It always returns nil and errors, if any, are added to the field's error list.

func (Field[T, V]) V

func (f Field[T, V]) V() any

V returns the field's value with "any" type.

func (Field[T, V]) Validators

func (f Field[T, V]) Validators() []Validator

Validators implements ValidatorsProvider and returns the value's validators.

func (Field[T, V]) Value

func (f Field[T, V]) Value() T

Value returns the field's Valuer value.

type FieldFlags

type FieldFlags byte

FieldFlags is a field's flag list.

const (
	// ValidatedField indicates a field has been validated.
	ValidatedField FieldFlags = 1 << iota
)

type FieldValidator

type FieldValidator interface {
	ValidateField(f Binder) error
}

FieldValidator describes a field validator (not its value).

type FieldValidatorFunc

type FieldValidatorFunc func(f Binder) error

FieldValidatorFunc is a FieldValidator.

func (FieldValidatorFunc) ValidateField

func (c FieldValidatorFunc) ValidateField(f Binder) error

ValidateField implements FieldValidator.

type File

type File FileOpener

File is a FileOpener holder.

type FileField

type FileField struct {
	Field[File, FileValue]
}

FileField is a field that holds a File value.

type FileListField

type FileListField ListField[File, ListValue[File, FileValue]]

FileListField is a field that holds a list of File values.

type FileOpener

type FileOpener interface {
	Open() (io.ReadCloser, error)
	Filename() string
	Size() int64
	Header() textproto.MIMEHeader
}

FileOpener describes an opener interface. Its [Open] function must return an io.ReadCloser.

type FileValue

type FileValue struct {
	BaseValue[File]
}

FileValue is a Valuer for uploaded files. It can open files submitted as multipart.FileHeader or strings from JSON or url values.

func (FileValue) String

func (v FileValue) String() string

func (*FileValue) UnmarshalFiles

func (v *FileValue) UnmarshalFiles(files []*multipart.FileHeader) error

UnmarshalFiles imlements FilesUnmarshaler. It decodes a the first file into a MultipartFileOpener.

func (*FileValue) UnmarshalJSON

func (v *FileValue) UnmarshalJSON(in []byte) error

UnmarshalJSON implements json.Unmarshaler. It decodes the content as a string and produces a StringOpener.

func (*FileValue) UnmarshalValues

func (v *FileValue) UnmarshalValues(values []string) error

UnmarshalValues implements ValuesUnmarshaler. It decodes the content as a string and produces a StringOpener.

type FilesUnmarshaler

type FilesUnmarshaler interface {
	UnmarshalFiles([]*multipart.FileHeader) error
}

FilesUnmarshaler is an interface implemented by types than can load a multipart.FileHeader list.

type FlagSetter

type FlagSetter interface {
	SetFlags(f ValueFlags)
}

FlagSetter describes a type that can sets its flags.

type Form

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

Form is our based type for form composition.

func (*Form) AddErrors

func (f *Form) AddErrors(errs ...error)

AddErrors adds errors to the form.

func (*Form) Bind

func (f *Form) Bind()

Bind marks the form as bound.

func (*Form) Context

func (f *Form) Context() context.Context

Context returns the form's context.

func (Form) Errors

func (f Form) Errors() Errors

Errors return a flat list of errors.

func (*Form) Fields

func (f *Form) Fields() map[string]Binder

Fields returns the form's registered Binder fields. Their respective name matches the name used during url.Values unmarshaling (with dot separated prefix and name for nested values).

func (*Form) IsBound

func (f *Form) IsBound() bool

IsBound returns whether the form is bound.

func (*Form) IsValid

func (f *Form) IsValid() bool

IsValid returns true when the form is valid.

func (*Form) MarshalJSON

func (f *Form) MarshalJSON() ([]byte, error)

MarshalJSON implement json.Marshaler.

func (*Form) MarshalValues

func (f *Form) MarshalValues() map[string]any

MarshalValues calls MarshalValues on the form's concrete instance.

func (*Form) SetContext

func (f *Form) SetContext(ctx context.Context)

SetContext sets the form's context. It implements ContextHolder.

func (*Form) SetFields

func (f *Form) SetFields(fields map[string]Binder)

SetFields is used by New and will panic if called more than once.

func (*Form) SetInstance

func (f *Form) SetInstance(instance FormBinder)

SetInstance is used by New and will panic if called more than once.

type FormBinder

type FormBinder interface {
	Fields() map[string]Binder
	Errors() Errors
	AddErrors(...error)
	IsBound() bool
	Bind()
	IsValid() bool
}

FormBinder is the interface implented by types that can act as a form.

type FormError

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

FormError is a form's or field's error that contains an error message and arguments.

func (FormError) Error

func (p FormError) Error() string

Error returns the untranslated error.

func (FormError) Is

func (p FormError) Is(err error) bool

Is implements error identification.

func (FormError) Translate

func (p FormError) Translate(tr Translator) string

Translate returns the translated error using the given translator.

func (FormError) Unwrap

func (p FormError) Unwrap() error

Unwrap implements error unwrap.

type IntegerField

type IntegerField = NumberField[int]

IntegerField is a field that holds an [int] value.

type IntegerListField

type IntegerListField = NumberListField[int]

IntegerListField is a field that holds a list of [int] values.

type ListField

type ListField[T any, V Valuer[[]T]] struct {
	Field[[]T, V]
}

ListField is a list field of items T with a matching Valuer. A ListField is not necessary for unmarshaling and you can simply use Field[[]T, ListValue[T, V]] for it to work. This type, however, applies the validators to each item.

func (*ListField[T, V]) IsValid

func (f *ListField[T, V]) IsValid() bool

IsValid first applies Field.IsValid and then perform the validation on each item.

type ListValue

type ListValue[T any, V Valuer[T]] struct {
	BaseValue[[]T]
}

ListValue is a generic Valuer for list of values. It works by wrapping unmarshal calls to the Valuer V and then set its own value from the collected results.

func (ListValue[T, V]) MarshalJSON

func (v ListValue[T, V]) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

func (ListValue[T, V]) String

func (v ListValue[T, V]) String() string

String returns a simple comma separated list of each values' String() result.

func (*ListValue[T, V]) UnmarshalFiles

func (v *ListValue[T, V]) UnmarshalFiles(files []*multipart.FileHeader) error

UnmarshalFiles implements FilesUnmarshaler. It only works on Valuer items implementing FilesUnmarshaler themselves.

func (*ListValue[T, V]) UnmarshalJSON

func (v *ListValue[T, V]) UnmarshalJSON(in []byte) error

UnmarshalJSON implements json.Unmarshaler.

func (*ListValue[T, V]) UnmarshalValues

func (v *ListValue[T, V]) UnmarshalValues(values []string) error

UnmarshalValues implements ValuesUnmarshaler.

type MimeType

type MimeType string

MimeType is a mime type forms can be loaded from.

const (
	MimeJSON       MimeType = "application/json"
	MimeURLEncoded MimeType = "application/x-www-form-urlencoded"
	MimeMultipart  MimeType = "multipart/form-data"
)

Common input mime types.

type MultipartFileOpener

type MultipartFileOpener struct {
	*multipart.FileHeader
}

MultipartFileOpener is a FileOpener implementation wrapping multipart.FileHeader.

func (*MultipartFileOpener) Filename

func (o *MultipartFileOpener) Filename() string

Filename implements FileOpener.

func (*MultipartFileOpener) Header

Header implements FileOpener.

func (*MultipartFileOpener) MarshalJSON

func (o *MultipartFileOpener) MarshalJSON() ([]byte, error)

MarshalJSON implement json.Marshaler.

func (*MultipartFileOpener) Open

func (o *MultipartFileOpener) Open() (io.ReadCloser, error)

Open implements FileOpener.

func (*MultipartFileOpener) Size

func (o *MultipartFileOpener) Size() int64

Size implements FileOpener.

type NoopTranslator

type NoopTranslator struct{}

NoopTranslator is a dummy translator.

func (NoopTranslator) Gettext

func (NoopTranslator) Gettext(s string, args ...any) string

Gettext implements Translator.

func (NoopTranslator) Pgettext

func (NoopTranslator) Pgettext(_, s string, args ...any) string

Pgettext implements Translator.

type NumberField

type NumberField[T numberType] struct {
	Field[T, NumberValue[T]]
	ChoicesField[T]
}

NumberField is a field that holds a given number type.

type NumberListField

type NumberListField[T numberType] struct {
	ListField[T, ListValue[T, NumberValue[T]]]
	ChoicesField[T]
}

NumberListField is a field that holds a list of number values.

type NumberValue

type NumberValue[T numberType] struct {
	BaseValue[T]
}

NumberValue is a Valuer for all int, uint and float types. Its decoder supports int and uint types with trailing zero decimals.

func (NumberValue[T]) String

func (v NumberValue[T]) String() string

String returns the number formatted according to its type.

func (*NumberValue[T]) UnmarshalJSON

func (v *NumberValue[T]) UnmarshalJSON(in []byte) error

UnmarshalJSON implements json.Unmarshaler.

func (*NumberValue[T]) UnmarshalValues

func (v *NumberValue[T]) UnmarshalValues(values []string) error

UnmarshalValues implements ValuesUnmarshaler.

type PivotListValue

type PivotListValue[T any, V Valuer[T], PT any, PV Valuer[PT]] struct {
	ListValue[T, V]
}

PivotListValue is a Valuer that holds a list of T items. Decoding uses an intermediate ListValue with PT type and PV Valuer. This is useful when you need to compose list of types but need some cleaners to run on the intermediate type first. For example, a URL list would be PivotListValue[url.URL, URLValue, string, StringValue].

func (*PivotListValue[T, V, PT, PV]) UnmarshalJSON

func (v *PivotListValue[T, V, PT, PV]) UnmarshalJSON(in []byte) error

UnmarshalJSON implements json.Unmarshaler.

func (*PivotListValue[T, V, PT, PV]) UnmarshalValues

func (v *PivotListValue[T, V, PT, PV]) UnmarshalValues(values []string) error

UnmarshalValues implements ValuesUnmarshaler.

type Setter

type Setter[T any] interface {
	Set(T)
}

Setter describes a type that can sets its value.

type SetterValuer

type SetterValuer[T any] interface {
	Valuer[T]
	Setter[T]
	FlagSetter
}

SetterValuer describes a Valuer, Setter and FlagSetter type.

type StringOpener

type StringOpener []byte

StringOpener is a FileOpener implementation using bytes.

func (StringOpener) Filename

func (o StringOpener) Filename() string

Filename implements FileOpener.

func (StringOpener) Header

func (o StringOpener) Header() textproto.MIMEHeader

Header implements FileOpener.

func (StringOpener) MarshalJSON

func (o StringOpener) MarshalJSON() ([]byte, error)

MarshalJSON implement json.Marshaler.

func (StringOpener) Open

func (o StringOpener) Open() (io.ReadCloser, error)

Open implements FileOpener.

func (StringOpener) Size

func (o StringOpener) Size() int64

Size implements FileOpener.

type StringValue

type StringValue = BaseValue[string]

StringValue is an alias to BaseValue for [string] type.

type TagContext

type TagContext struct {
	Form    FormBinder
	Field   Binder
	Context context.Context
}

TagContext is the parameter passed to a tagged validation function.

type TaggedValidatorFunc

type TaggedValidatorFunc func(name, args string, tc *TagContext) (Validator, bool)

TaggedValidatorFunc is a function called to get a Validator from a tag. The function returns a Validator (can be nil) and whether the name was found.

type TaggedValidatorProvider

type TaggedValidatorProvider interface {
	GetTaggedValidator(name, args string, tc *TagContext) (Validator, bool)
}

TaggedValidatorProvider is an interface that describes a type providing its custom tagged validators.

type TextField

type TextField struct {
	Field[string, StringValue]
	ChoicesField[string]
}

TextField is a field that holds a [string] value.

type TextListField

type TextListField struct {
	ListField[string, ListValue[string, StringValue]]
	ChoicesField[string]
}

TextListField is a field that holds a list of [string] values.

type Translator

type Translator interface {
	Gettext(string, ...any) string
	Pgettext(ctx, str string, vars ...any) string
}

Translator describes a type that implements a translation method.

func GetTranslator

func GetTranslator(ctx context.Context) Translator

GetTranslator returns the Translator from the context.

type TranslatorProvider

type TranslatorProvider interface {
	Translator() Translator
	SetTranslator(Translator)
}

TranslatorProvider describes a type that can store and return a Translator.

type TypedBinder

type TypedBinder[T any] interface {
	Binder
	Value() T
}

TypedBinder describes a Binder with its Value method.

type URLField

type URLField = Field[url.URL, URLValue]

URLField is a field that holds a url.URL value.

type URLListField

URLListField is a field that holds a list of url.URL values.

type URLValue

type URLValue struct {
	BaseValue[url.URL]
}

URLValue is a Valuer that can decode url.URL values. Input values are decoded using url.Parse and no further URL validation is performed.

func (URLValue) MarshalJSON

func (v URLValue) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

func (URLValue) String

func (v URLValue) String() string

func (*URLValue) UnmarshalJSON

func (v *URLValue) UnmarshalJSON(in []byte) error

UnmarshalJSON decodes an url.URL from a JSON string.

func (*URLValue) UnmarshalValues

func (v *URLValue) UnmarshalValues(values []string) error

UnmarshalValues decoded an url.URL from a value string.

type URLValuesUnmarshaler

type URLValuesUnmarshaler interface {
	UnmarshalValues(url.Values) error
}

URLValuesUnmarshaler is an interface implemented by types with a custom url.Values decoder. This can be implemented by a Form instance for special use cases.

type ValidateChecker

type ValidateChecker interface {
	Validate() error
}

ValidateChecker describes a type that can bring its own validation method. The returned error is added to the error list. To return several errors at once, one can use Errors or errors.Join.

type Validator

type Validator any

Validator describes a generic validator. By default, it can be anything but, once attached to a field, relevant interfaces are called during cleanup and validation steps.

type ValidatorProvider

type ValidatorProvider interface {
	IsValid() bool
}

ValidatorProvider describes a type that provides a validation check method.

type ValidatorsProvider

type ValidatorsProvider interface {
	Validators() []Validator
	SetValidators(validators []Validator)
}

ValidatorsProvider is an interface implemented by types than can store and return a list of Validator.

type ValueChoice

type ValueChoice[T comparable] struct {
	Name  string
	Value T
}

ValueChoice is a key/value pair used by ValueChoices.

func Choice

func Choice[T comparable](name string, value T) ValueChoice[T]

Choice returns a new ValueChoice instance.

func (ValueChoice[T]) In

func (c ValueChoice[T]) In(values []T) bool

In returns true when the choice is present in a list of values.

type ValueChoices

type ValueChoices[T comparable] []ValueChoice[T]

ValueChoices is a key/value pair and also a ValueValidator. It can be set directly as a validator to limit the possible choices. To set the validator and have the choice list available, see Choices.

func (ValueChoices[T]) String

func (c ValueChoices[T]) String() string

func (ValueChoices[T]) ValidateValue

func (c ValueChoices[T]) ValidateValue(f Binder, v T) error

ValidateValue checks that the value v exists in the choices.

type ValueCleaner

type ValueCleaner[T any] interface {
	Clean(T) T
}

ValueCleaner describes a value cleaner.

type ValueFlags

type ValueFlags byte

ValueFlags holds the flags a value can get.

const (
	// IsEmpty is the flag for an empty value.
	IsEmpty ValueFlags = 1 << iota
	// IsBound is the flag for a bound value.
	IsBound
	// IsNil is the flag for a nil value.
	IsNil
)

func (ValueFlags) IsBound

func (f ValueFlags) IsBound() bool

IsBound returns true when IsBound is present in the flags.

func (ValueFlags) IsEmpty

func (f ValueFlags) IsEmpty() bool

IsEmpty returns true when IsEmpty is present in the flags.

func (ValueFlags) IsNil

func (f ValueFlags) IsNil() bool

IsNil returns true when IsNil is present in the flags.

type ValueValidator

type ValueValidator[T any] interface {
	ValidateValue(f Binder, v T) error
}

ValueValidator describes a value validator.

func Gte

func Gte(n float64) ValueValidator[any]

Gte is an integer validator that checks if a value is greater or equal than a parameter.

func IsURL

func IsURL(schemes ...string) ValueValidator[any]

IsURL checks that the input value is a valid URL that matches the given schemes and has a hostname. It works on [string] and url.URL values.

func Len

func Len(n int) ValueValidator[string]

Len is a string validator thats checks if it contains exactly n characters.

func Lte

func Lte(n float64) ValueValidator[any]

Lte is an integer validator that checks if a value is lower or equal than a parameter.

func MaxLen

func MaxLen(n int) ValueValidator[string]

MaxLen is a string validator thats checks if it contains at most n characters.

func MinLen

func MinLen(n int) ValueValidator[string]

MinLen is a string validator thats checks if it contains at least n characters.

func TypedValidator

func TypedValidator[T any](validator func(T) bool, err error) ValueValidator[T]

TypedValidator is a helper function that returns a ValueValidator from a validation function and an error message. The resulting validator only applies on a bound or not null field.

type ValueValidatorFunc

type ValueValidatorFunc[T any] func(f Binder, v T) error

ValueValidatorFunc is a ValueValidator.

func (ValueValidatorFunc[T]) ValidateValue

func (c ValueValidatorFunc[T]) ValidateValue(f Binder, v T) error

ValidateValue implements ValueValidator.

type Valuer

type Valuer[T any] interface {
	fmt.Stringer
	json.Marshaler

	Value() T
	Flags() ValueFlags
	IsBound() bool
	IsNil() bool
	IsEmpty() bool
}

Valuer is the interface implemented by types that can load and decode input data.

type ValuesUnmarshaler

type ValuesUnmarshaler interface {
	UnmarshalValues([]string) error
}

ValuesUnmarshaler is an interface implemented by types with a custom url.Values item decoder.

Jump to

Keyboard shortcuts

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