encoding

package
v14.0.1 Latest Latest
Warning

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

Go to latest
Published: Nov 13, 2026 License: BSD-3-Clause Imports: 18 Imported by: 0

Documentation

Index

Constants

View Source
const DefaultContextValueTag = "context"

DefaultContextValueTag is the default struct tag to look for context values. Defaults to "context".

View Source
const DefaultFormTag = "form"

DefaultFormTag is the default struct tag for form. Defaults to "form".

View Source
const DefaultHeaderTag = "header"

DefaultHeaderTag is the default struct tag for header. Defaults to "header".

View Source
const DefaultPathParamTag = "param"

DefaultPathParamTag is the default struct tag to look for path params. Defaults to "param".

View Source
const (

	// DefaultQueryEntrySep is the default separator used to join values as single string from the map.
	// See Entries.ToQuery.
	DefaultQueryEntrySep = ","
)
View Source
const DefaultQueryTag = "url"

DefaultQueryTag is the default struct tag for url query. Defaults to "url".

Variables

View Source
var (
	// ErrParamNotWeekday is fired when the parameter value is not a form of a time.Weekday.
	ErrParamNotWeekday = fmt.Errorf("parameter is not a valid weekday")

	// ParseWeekday is a helper function that can be used to parse a weekday string.
	ParseWeekday = func(paramValue string) (time.Weekday, error) {
		d, ok := longDayNames[paramValue]
		if !ok {

			n, err := strconv.Atoi(paramValue)
			if err != nil {
				return -1, fmt.Errorf("%s: %w", paramValue, err)
			}

			if n < 0 || n > 6 {
				return -1, fmt.Errorf("%s: %w", paramValue, ErrParamNotWeekday)
			}

			return time.Weekday(n), nil
		}

		return d, nil
	}
)
View Source
var DefaultQueryFieldSetter = func(field *reflect.StructField, ptr unsafe.Pointer, values []string) error {
	switch field.Type {
	case reflex.StringType:
		*(*string)(ptr) = values[0]
	case reflex.IntType:
		intVal, err := strconv.Atoi(values[0])
		if err != nil {
			return err
		}
		*(*int)(ptr) = intVal
	case reflex.Int8Type:
		intVal, err := strconv.ParseInt(values[0], 10, 8)
		if err != nil {
			return err
		}
		*(*int8)(ptr) = int8(intVal)
	case reflex.Int16Type:
		intVal, err := strconv.ParseInt(values[0], 10, 16)
		if err != nil {
			return err
		}
		*(*int16)(ptr) = int16(intVal)
	case reflex.Int32Type:
		intVal, err := strconv.ParseInt(values[0], 10, 32)
		if err != nil {
			return err
		}
		*(*int32)(ptr) = int32(intVal)
	case reflex.Int64Type:
		intVal, err := strconv.ParseInt(values[0], 10, 64)
		if err != nil {
			return err
		}
		*(*int64)(ptr) = intVal
	case reflex.UintType:
		uintVal, err := strconv.ParseUint(values[0], 10, 64)
		if err != nil {
			return err
		}
		*(*uint)(ptr) = uint(uintVal)
	case reflex.Uint8Type:
		uintVal, err := strconv.ParseUint(values[0], 10, 8)
		if err != nil {
			return err
		}
		*(*uint8)(ptr) = uint8(uintVal)
	case reflex.Uint16Type:
		uintVal, err := strconv.ParseUint(values[0], 10, 16)
		if err != nil {
			return err
		}
		*(*uint16)(ptr) = uint16(uintVal)
	case reflex.Uint32Type:
		uintVal, err := strconv.ParseUint(values[0], 10, 32)
		if err != nil {
			return err
		}
		*(*uint32)(ptr) = uint32(uintVal)
	case reflex.Uint64Type:
		uintVal, err := strconv.ParseUint(values[0], 10, 64)
		if err != nil {
			return err
		}
		*(*uint64)(ptr) = uintVal
	case reflex.Float32Type:
		floatVal, err := strconv.ParseFloat(values[0], 32)
		if err != nil {
			return err
		}
		*(*float32)(ptr) = float32(floatVal)
	case reflex.Float64Type:
		floatVal, err := strconv.ParseFloat(values[0], 64)
		if err != nil {
			return err
		}
		*(*float64)(ptr) = floatVal
	case reflex.BoolType:
		boolVal, err := strconv.ParseBool(values[0])
		if err != nil {
			return err
		}
		*(*bool)(ptr) = boolVal
	case reflex.ArrayStringTyp:
		*(*[]string)(ptr) = values
	case reflex.ArrayIntegerTyp:
		intValues := make([]int, len(values))
		for i, v := range values {
			intVal, err := strconv.Atoi(v)
			if err != nil {
				return err
			}
			intValues[i] = intVal
		}
		*(*[]int)(ptr) = intValues
	case reflex.TimeType:
		t, err := time.Parse(time.RFC3339, values[0])
		if err != nil {
			return err
		}
		*(*time.Time)(ptr) = t
	case reflex.WeekdayType:
		weekday, err := strconv.Atoi(values[0])
		if err != nil {
			return err
		}
		*(*time.Weekday)(ptr) = time.Weekday(weekday)
	case reflex.UUIDType:
		id, err := uuid.Parse(values[0])
		if err != nil {
			return err
		}
		*(*uuid.UUID)(ptr) = id
	case reflex.DurationType:
		d, err := time.ParseDuration(values[0])
		if err != nil {
			return err
		}
		*(*time.Duration)(ptr) = d
	default:
		return fmt.Errorf("%w: %s", ErrUnsupportedType, field.Type.String())
	}

	return nil
}

DefaultQueryFieldSetter is the default field setter for url query values.

View Source
var ErrTypeMismatch = fmt.Errorf("type mismatch")

ErrTypeMismatch is returned when a decoded value's type does not match the destination struct field's type.

View Source
var ErrUnsupportedType = fmt.Errorf("unsupported type")
View Source
var ParseDate = func(paramValue string) (time.Time, error) {
	tt, err := time.Parse(simpleDateLayout, paramValue)
	if err != nil {
		tt2, err2 := time.Parse(simpleDateLayout2, paramValue)
		if err2 != nil {
			return zeroDate, fmt.Errorf("%s: failed to parse time (2006/01/02, 2006-01-02): %w, %w", paramValue, err, err2)
		}

		tt = tt2
	}

	return tt, nil
}

ParseDate is a helper function that can be used to parse a date string.

View Source
var ParseTime = func(paramValue string) (time.Time, error) {
	return time.Parse(time.RFC3339, paramValue)
}

ParseTime is a helper function that can be used to parse a time string. It accepts the RFC 3339 form ("2006-01-02T15:04:05Z07:00"), with or without fractional seconds. Replace it to accept other layouts through Entry.Time.

Functions

func DecodeQuery

func DecodeQuery(path string) string

DecodeQuery returns the uri parameter as url (string) useful when you want to pass something to a database and be valid to retrieve it via context.Param use it only for special cases, when the default behavior doesn't suits you.

http://www.blooberry.com/indexdot/html/topics/urlencoding.htm it uses just the url.QueryUnescape

func DefaultPathFieldSetter

func DefaultPathFieldSetter[V any](field *reflect.StructField, ptr unsafe.Pointer, value V) error

DefaultPathFieldSetter is the default field setter for context values or path params.

Note(@kataras): every branch dispatches on the FIELD's declared type, never on the value's runtime type, because "ptr" points at the field and the write size is decided by the type we cast it to. Dispatching on the value would let a path parameter that the macro evaluator produced as a string (the type of an untyped "{id}") be written as a 16-byte string header over, say, an 8-byte int64 field - clobbering the next field with a client-controlled value.

func GobEncode

func GobEncode[T any](store Entries[T], w io.Writer) error

GobEncode accepts a store and writes as series of bytes to the "w" writer.

func GobEncodeEntry

func GobEncodeEntry[T any](entry Entry[T], w io.Writer) error

GobEncodeEntry accepts an entry and writes as series of bytes to the "w" writer.

func GobSerialize

func GobSerialize[T any](store Entries[T]) ([]byte, error)

GobSerialize same as GobEncode but it returns the bytes using a temp buffer.

func GobSerializeEntry

func GobSerializeEntry[T any](entry Entry[T]) ([]byte, error)

GobSerializeEntry same as GobEncodeEntry but it returns the bytes using a temp buffer.

Types

type ContextValues

type ContextValues = Entries[any]

ContextValues is a slice of Entry. It's used by the Context to store custom key-values for middleware communication.

type ContextValuesDecoderOptions

type ContextValuesDecoderOptions = EntriesDecoderOptions[any]

ContextValuesDecoderOptions is the options for the context values decoder.

type Entries

type Entries[V any] []Entry[V] // no pointer to Entry, as they are small and we don't want to allocate memory for each of them.

Entries is a slice of Entry.

func GobDecode

func GobDecode[T any](b []byte) (store Entries[T], err error)

GobDecode accepts a series of bytes and returns the store.

func (*Entries[V]) Add

func (e *Entries[V]) Add(key string, value V)

Add adds a key-value pair to the entries.

func (*Entries[V]) AddEntry

func (e *Entries[V]) AddEntry(entryToAdd Entry[V])

AddEntry adds a key-value pair (a Entry) to the entries.

func (Entries[V]) Bind

func (e Entries[V]) Bind(key string, ptr *V) bool

Bind binds the value of a key to a pointer.

func (Entries[V]) Clone

func (e Entries[V]) Clone() Entries[V]

Clone returns a new copy of the request entries.

func (Entries[V]) Exists

func (e Entries[V]) Exists(key string) bool

Exists reports whether the key exists in the request entries.

func (Entries[V]) ForEach

func (e Entries[V]) ForEach(fn func(key string, value V))

ForEach traverses the request entries and calls the given function.

func (Entries[V]) ForEachString

func (e Entries[V]) ForEachString(fn func(key string, value string))

ForEachString traverses the request entries and calls the given function. It converts the value to string before calling the function.

func (Entries[V]) Get

func (e Entries[V]) Get(key string) V

Get returns the value of a key.

Use `GetEntry` if you want to get the key-value pair. Use `Lookup` if you want to retrieve the raw value and check if the key exists. Use `GetString` if you want to get the value as string.

func (Entries[V]) GetBool

func (e Entries[V]) GetBool(key string) bool

GetBool returns the value of a key as bool.

func (Entries[V]) GetByIndex

func (e Entries[V]) GetByIndex(index int) (string, bool)

GetByIndex returns the value as string of a key by its index.

func (Entries[V]) GetByte

func (e Entries[V]) GetByte(key string) byte

GetByte returns the value of a key as byte.

func (Entries[V]) GetDate

func (e Entries[V]) GetDate(key string) time.Time

GetDate returns the value of a key as time.Time.

func (Entries[V]) GetDuration

func (e Entries[V]) GetDuration(key string) time.Duration

GetDuration returns the value of a key as time.Duration. A string value is parsed with time.ParseDuration ("30s", "1h30m"). It returns 0 if the key does not exist or its value is not a duration.

func (Entries[V]) GetEntry

func (e Entries[V]) GetEntry(key string) (Entry[V], bool)

GetEntry returns the key-value of a key.

func (Entries[V]) GetEntryByIndex

func (e Entries[V]) GetEntryByIndex(index int) (Entry[V], bool)

GetEntryByIndex returns the key-value pair by its index. It returns false if the index is out of range.

func (Entries[V]) GetEscape

func (e Entries[V]) GetEscape(key string) string

GetEscape returns the value as string but it decodes it first as url query.

func (Entries[V]) GetFloat32

func (e Entries[V]) GetFloat32(key string) float32

GetFloat32 returns the value of a key as float32.

func (Entries[V]) GetFloat64

func (e Entries[V]) GetFloat64(key string) float64

GetFloat64 returns the value of a key as float64.

func (Entries[V]) GetIP

func (e Entries[V]) GetIP(key string) netip.Addr

GetIP returns the value of a key as netip.Addr. A string value is parsed with netip.ParseAddr. It returns the zero netip.Addr, for which IsValid reports false, if the key does not exist or its value is not an IP address.

func (Entries[V]) GetInt

func (e Entries[V]) GetInt(key string) int

GetInt returns the value of a key as int.

func (Entries[V]) GetInt8

func (e Entries[V]) GetInt8(key string) int8

GetInt8 returns the value of a key as int8.

func (Entries[V]) GetInt16

func (e Entries[V]) GetInt16(key string) int16

GetInt16 returns the value of a key as int16.

func (Entries[V]) GetInt32

func (e Entries[V]) GetInt32(key string) int32

GetInt32 returns the value of a key as int32.

func (Entries[V]) GetInt64

func (e Entries[V]) GetInt64(key string) int64

GetInt64 returns the value of a key as int64.

func (Entries[V]) GetIntUnslashed

func (e Entries[V]) GetIntUnslashed(key string) int

GetIntUnslashed returns the value as int but without the first slash if found. It returns -1 if the value wasn't found or it is not a valid int.

func (Entries[V]) GetLastEntry

func (e Entries[V]) GetLastEntry() (Entry[V], bool)

GetLastEntry returns the last key-value pair. It returns false if the request entries are empty.

func (Entries[V]) GetPointer

func (e Entries[V]) GetPointer(key string) unsafe.Pointer

GetPointer returns the pointer of a key or nil.

func (Entries[V]) GetRune

func (e Entries[V]) GetRune(key string) rune

GetRune returns the value of a key as rune.

func (Entries[V]) GetString

func (e Entries[V]) GetString(key string) string

GetString returns the value of a key as string. It returns an empty string if the key does not exist.

func (Entries[V]) GetStringSlice

func (e Entries[V]) GetStringSlice(key string) []string

GetStringSlice returns the value of a key as []string. It returns nil if the key does not exist.

func (Entries[V]) GetTime

func (e Entries[V]) GetTime(key string) time.Time

GetTime returns the value of a key as time.Time, a point in time. A string value is parsed with ParseTime (RFC 3339, "2006-01-02T15:04:05Z07:00"). For a calendar day see GetDate. It returns the zero time.Time if the key does not exist or its value is not a time.

func (Entries[V]) GetTrim

func (e Entries[V]) GetTrim(key string) string

GetTrim returns the value as string but it trims the spaces.

func (Entries[V]) GetTrimFile

func (e Entries[V]) GetTrimFile(key string) string

GetTrimFile returns a value without the last ".ext" part.

func (Entries[V]) GetTrimFileInt

func (e Entries[V]) GetTrimFileInt(key string) int

GetTrimFileInt same as GetTrimFile but it returns the value as int.

func (Entries[V]) GetTrimHTML

func (e Entries[V]) GetTrimHTML(key string) string

GetTrimHTML returns a value without the last ".html" part.

func (Entries[V]) GetTrimJSON

func (e Entries[V]) GetTrimJSON(key string) string

GetTrimJSON returns a value without the last ".json" part.

func (Entries[V]) GetTrimXML

func (e Entries[V]) GetTrimXML(key string) string

GetTrimXML returns a value without the last ".xml" part.

func (Entries[V]) GetUUID

func (e Entries[V]) GetUUID(key string) uuid.UUID

GetUUID returns the value of a key as uuid.UUID. A string value is parsed with uuid.Parse. It returns the zero UUID if the key does not exist or its value is not a UUID.

func (Entries[V]) GetUint

func (e Entries[V]) GetUint(key string) uint

GetUint returns the value of a key as uint.

func (Entries[V]) GetUint8

func (e Entries[V]) GetUint8(key string) uint8

GetUint8 returns the value of a key as uint8.

func (Entries[V]) GetUint16

func (e Entries[V]) GetUint16(key string) uint16

GetUint16 returns the value of a key as uint16.

func (Entries[V]) GetUint32

func (e Entries[V]) GetUint32(key string) uint32

GetUint32 returns the value of a key as uint32.

func (Entries[V]) GetUint64

func (e Entries[V]) GetUint64(key string) uint64

GetUint64 returns the value of a key as uint64.

func (Entries[V]) GetWeekday

func (e Entries[V]) GetWeekday(key string) time.Weekday

GetWeekday returns the value of a key as time.Weekday.

func (Entries[V]) Len

func (e Entries[V]) Len() int

Len returns the length of the request entries.

func (Entries[V]) Lookup

func (e Entries[V]) Lookup(key string) (V, bool)

Lookup returns the value of a key. It returns false if the key does not exist.

func (Entries[V]) LookupByIndex

func (e Entries[V]) LookupByIndex(index int) (V, bool)

LookupByIndex returns the value of a key by its index. It returns false if the key does not exist.

func (Entries[V]) MergeQuery

func (e Entries[V]) MergeQuery(extra url.Values) url.Values

MergeQuery merges the request entries with an extra url.Values.

func (*Entries[V]) Pop

func (e *Entries[V]) Pop(key string) V

Pop deletes an entry based on the given "key" from the entries and returns the value of the deleted entry.

func (*Entries[V]) PopPointer

func (e *Entries[V]) PopPointer(key string) unsafe.Pointer

PopPointer deletes an entry based on the given "key" from the entries and returns the unsafe.Pointer of the deleted entry.

func (*Entries[V]) Remove

func (e *Entries[V]) Remove(key string) bool

Remove deletes a key from the entries, order is not changed.

func (*Entries[V]) Replace

func (e *Entries[V]) Replace(key string, value V) bool

Replace replaces the value of a key with a new value. Reports whether the key was found and the value was replaced.

func (*Entries[V]) Reset

func (e *Entries[V]) Reset()

Reset clears all the request entries.

func (*Entries[V]) Set

func (e *Entries[V]) Set(key string, value V)

Set sets a key-value pair to the request entries. If the key already exists and it is not immutable, it replaces the value; an entry stored through SetImmutable is left untouched and no error is reported. If the key does not exist, it appends the key-value pair.

func (*Entries[V]) SetByIndex

func (e *Entries[V]) SetByIndex(index int, value V)

SetByIndex sets the value of a key by its index. Replaces any existing value, even if it was immutable.

func (*Entries[V]) SetEntryByIndex

func (e *Entries[V]) SetEntryByIndex(index int, entry Entry[V])

SetEntryByIndex sets a key-value pair (a Entry) to the entries by its index. Replaces any existing value, even if it was immutable.

func (*Entries[V]) SetImmutable

func (e *Entries[V]) SetImmutable(key string, value V)

SetImmutable sets a key-value pair to the request entries. If the key already exists and it is not already immutable, it replaces the value; an entry which is already immutable is left untouched and no error is reported. If the key does not exist, it appends the key-value pair. The stored value cannot be changed by Set, SetImmutable or Replace afterwards, it can only be removed (see Remove and Pop) or overwritten by its index (see SetByIndex and SetEntryByIndex).

func (Entries[V]) ToMap

func (e Entries[V]) ToMap() map[string][]string

ToMap converts the request entries to a map[string][]string. Uses the separator given for each entry.

func (Entries[V]) ToQuery

func (e Entries[V]) ToQuery() url.Values

ToQuery converts the request entries to a url.Values. Uses the "," separator.

func (Entries[V]) WithoutDefaults

func (e Entries[V]) WithoutDefaults() Entries[V]

WithoutDefaults returns a new Entries without the default (builtin by the framework) key-values.

type EntriesDecoder

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

EntriesDecoder decodes the context values or path params to the target struct value of T. Create one through the `NewEntriesDecoder` package-level function and use its `DecodeEntries` method.

func NewContextValuesDecoder

func NewContextValuesDecoder[T any](opts ContextValuesDecoderOptions) (*EntriesDecoder[T, any], error)

NewContextValuesDecoder returns a new context values decoder. It returns an error if T is not a pointer to a struct. The options can be empty. See `EntriesDecoderOptions` struct and its `DecodeEntries` method for more.

func NewEntriesDecoder

func NewEntriesDecoder[T, V any](opts EntriesDecoderOptions[V]) (*EntriesDecoder[T, V], error)

NewEntriesDecoder returns a new entries decoder. It returns an error if T is not a struct type, the decoder forms the *T target by itself. The options can be empty. See `EntriesDecoderOptions` struct and its `DecodeEntries` method for more.

func NewPathParamsDecoder

func NewPathParamsDecoder[T any](opts PathParamsDecoderOptions) (*EntriesDecoder[T, any], error)

NewPathParamsDecoder returns a new path params decoder. It returns an error if T is not a pointer to a struct. The options can be empty. See `EntriesDecoderOptions` struct and its `DecodeEntries` method for more.

func (*EntriesDecoder[T, V]) DecodeEntries

func (d *EntriesDecoder[T, V]) DecodeEntries(store Entries[V], target *T) error

DecodeEntries decodes the context values or path params to the target struct value of T.

func (*EntriesDecoder[T, V]) HasRequired

func (d *EntriesDecoder[T, V]) HasRequired() bool

HasRequired reports whether the decoder has at least one required field.

type EntriesDecoderOptions

type EntriesDecoderOptions[V any] struct {
	// FieldTag is the struct tag to look.
	FieldTag string
	// Strict is a flag that determines the behavior of the decoder when it encounters an unknown path param.
	// If true then it should not have any extra or missing fields. Marks all fields as required.
	// Defaults to false.
	Strict bool
	// FieldSetter is the field setter function.
	// Defaults to DefaultPathFieldSetter.
	FieldSetter FieldSetter[V]
}

EntriesDecoderOptions is the options for the path params decoder. See `NewEntriesDecoder` package-level function for more.

type Entry

type Entry[V any] struct {
	// Key is the key of the entry.
	Key string `json:"key" yaml:"Key" toml:"Key" ini:"key" env:"key"` // we could accept a K,V and constraint the K with comparable but we don't want to force the user to use a specific type for the key.
	// Value is the value of the entry.
	Value V `json:"value" yaml:"Value" toml:"Value" ini:"value" env:"value"` // the Value may be converted from and to specific type, usually by a TypeEvaluator on the TemplateParam of macros. Until then it's usually string unless context.Values.
	// Immutable indicates if the value is immutable.
	Immutable bool `json:"immutable" yaml:"Immutable" toml:"Immutable" ini:"immutable" env:"immutable"` // if true then it can't be changed by SetImmutable, Set or Replace.

	// Sep is optional separator.
	// It is used to split the string value to []string when the underline value is not a []string.
	// It is used on ToMap() of the Entries structure too.
	// It defaults to '/'.
	Sep string
}

Entry is a key string - value any storage.

func GobDecodeEntry

func GobDecodeEntry[T any](b []byte) (entry Entry[T], err error)

GobDecodeEntry accepts a series of bytes and returns the entry.

func (*Entry[V]) Bool

func (e *Entry[V]) Bool() bool

Bool returns the value as bool. A string value is parsed by strconv.ParseBool. It returns false for any other type and for a string that does not parse.

func (*Entry[V]) Byte

func (e *Entry[V]) Byte() byte

Byte returns the value as byte. A value stored as any other Go numeric is converted when it survives the conversion intact, and a numeric string is parsed. It returns 0 otherwise.

func (*Entry[V]) Date

func (e *Entry[V]) Date() time.Time

Date returns the value as time.Time (year/month/day). A string value is passed through ParseDate first. It returns the zero time.Time if the value is neither a time.Time nor a parsable date string.

func (*Entry[V]) Duration

func (e *Entry[V]) Duration() time.Duration

Duration returns the value as time.Duration. A string value is passed through time.ParseDuration ("30s", "1h30m"). A number is not a duration, because it carries no unit. It returns 0 if the value is neither a time.Duration nor a parsable string.

func (*Entry[V]) Escape

func (e *Entry[V]) Escape() string

Escape returns the value as string but it decodes it first as url query.

func (*Entry[V]) Float32

func (e *Entry[V]) Float32() float32

Float32 returns the value as float32. A value stored as any other Go numeric is converted when it survives the conversion intact, and a numeric string is parsed. It returns 0 otherwise.

func (*Entry[V]) Float64

func (e *Entry[V]) Float64() float64

Float64 returns the value as float64. A value stored as any other Go numeric is converted when it survives the conversion intact, and a numeric string is parsed. It returns 0 otherwise.

func (*Entry[V]) GetBool

func (e *Entry[V]) GetBool() (bool, bool)

func (*Entry[V]) GetByte

func (e *Entry[V]) GetByte() (byte, bool)

func (*Entry[V]) GetDate

func (e *Entry[V]) GetDate() (time.Time, bool)

GetDate returns the value as time.Time. It returns false if the value is not a time.Time.

func (*Entry[V]) GetDuration

func (e *Entry[V]) GetDuration() (time.Duration, bool)

GetDuration returns the value as time.Duration. It returns false if the value is not a time.Duration.

func (*Entry[V]) GetFloat32

func (e *Entry[V]) GetFloat32() (float32, bool)

func (*Entry[V]) GetFloat64

func (e *Entry[V]) GetFloat64() (float64, bool)

func (*Entry[V]) GetIP

func (e *Entry[V]) GetIP() (netip.Addr, bool)

GetIP returns the value as netip.Addr. It returns false if the value is not a netip.Addr.

func (*Entry[V]) GetInt

func (e *Entry[V]) GetInt() (int, bool)

func (*Entry[V]) GetInt8

func (e *Entry[V]) GetInt8() (int8, bool)

func (*Entry[V]) GetInt16

func (e *Entry[V]) GetInt16() (int16, bool)

func (*Entry[V]) GetInt32

func (e *Entry[V]) GetInt32() (int32, bool)

func (*Entry[V]) GetInt64

func (e *Entry[V]) GetInt64() (int64, bool)

func (*Entry[V]) GetRune

func (e *Entry[V]) GetRune() (rune, bool)

func (*Entry[V]) GetString

func (e *Entry[V]) GetString() (string, bool)

GetString returns the value as string. It returns false if the value is not a string.

func (*Entry[V]) GetStringSlice

func (e *Entry[V]) GetStringSlice() ([]string, bool)

func (*Entry[V]) GetTime

func (e *Entry[V]) GetTime() (time.Time, bool)

GetTime returns the value as time.Time. It returns false if the value is not a time.Time.

func (*Entry[V]) GetTrim

func (e *Entry[V]) GetTrim() string

GetTrim returns the value as string but it trims the spaces.

func (*Entry[V]) GetUUID

func (e *Entry[V]) GetUUID() (uuid.UUID, bool)

GetUUID returns the value as uuid.UUID. It returns false if the value is not a uuid.UUID.

func (*Entry[V]) GetUint

func (e *Entry[V]) GetUint() (uint, bool)

func (*Entry[V]) GetUint8

func (e *Entry[V]) GetUint8() (uint8, bool)

func (*Entry[V]) GetUint16

func (e *Entry[V]) GetUint16() (uint16, bool)

func (*Entry[V]) GetUint32

func (e *Entry[V]) GetUint32() (uint32, bool)

func (*Entry[V]) GetUint64

func (e *Entry[V]) GetUint64() (uint64, bool)

func (*Entry[V]) GetWeekday

func (e *Entry[V]) GetWeekday() (time.Weekday, bool)

GetWeekday returns the value as time.Weekday. It returns false if the value is not a time.Weekday.

func (*Entry[V]) IP

func (e *Entry[V]) IP() netip.Addr

IP returns the value as netip.Addr. A string value is passed through netip.ParseAddr ("10.0.0.1", "::1", "fe80::1%eth0"). An address with a port or a host name is not an IP address. It returns the zero netip.Addr, for which IsValid reports false, if the value is neither a netip.Addr nor a parsable string.

func (*Entry[V]) Int

func (e *Entry[V]) Int() int

Int returns the value as int. A value stored as any other Go numeric is converted when it survives the conversion intact, and a numeric string is parsed. It returns 0 otherwise.

func (*Entry[V]) Int8

func (e *Entry[V]) Int8() int8

Int8 returns the value as int8. A value stored as any other Go numeric is converted when it survives the conversion intact, and a numeric string is parsed. It returns 0 otherwise.

func (*Entry[V]) Int16

func (e *Entry[V]) Int16() int16

Int16 returns the value as int16. A value stored as any other Go numeric is converted when it survives the conversion intact, and a numeric string is parsed. It returns 0 otherwise.

func (*Entry[V]) Int32

func (e *Entry[V]) Int32() int32

Int32 returns the value as int32. A value stored as any other Go numeric is converted when it survives the conversion intact, and a numeric string is parsed. It returns 0 otherwise.

func (*Entry[V]) Int64

func (e *Entry[V]) Int64() int64

Int64 returns the value as int64. A value stored as any other Go numeric is converted when it survives the conversion intact, and a numeric string is parsed. It returns 0 otherwise.

func (*Entry[V]) IntUnslashed

func (e *Entry[V]) IntUnslashed() int

IntUnslashed returns the value as int but without the first slash if found. It returns -1 if the value is empty or is not a valid int.

func (*Entry[V]) IsDefault

func (e *Entry[V]) IsDefault() bool

IsDefault reports whether the entry is an entry constructed by the framework itself and no by the end-developer.

func (*Entry[V]) MustBool

func (e *Entry[V]) MustBool() bool

MustBool returns the value as bool. It panics if the value is not a bool.

func (*Entry[V]) MustByte

func (e *Entry[V]) MustByte() byte

MustByte returns the value as byte. It panics if the value is not a byte.

func (*Entry[V]) MustDate

func (e *Entry[V]) MustDate() time.Time

MustDate returns the value as time.Time. It panics if the value is not a time.Time.

func (*Entry[V]) MustDuration

func (e *Entry[V]) MustDuration() time.Duration

MustDuration returns the value as time.Duration. It panics if the value is not a time.Duration.

func (*Entry[V]) MustFloat32

func (e *Entry[V]) MustFloat32() float32

MustFloat32 returns the value as float32. It panics if the value is not a float32.

func (*Entry[V]) MustFloat64

func (e *Entry[V]) MustFloat64() float64

MustFloat64 returns the value as float64. It panics if the value is not a float64.

func (*Entry[V]) MustIP

func (e *Entry[V]) MustIP() netip.Addr

MustIP returns the value as netip.Addr. It panics if the value is not a netip.Addr.

func (*Entry[V]) MustInt

func (e *Entry[V]) MustInt() int

MustInt returns the value as int. It panics if the value is not an int.

func (*Entry[V]) MustInt8

func (e *Entry[V]) MustInt8() int8

MustInt8 returns the value as int8. It panics if the value is not an int8.

func (*Entry[V]) MustInt16

func (e *Entry[V]) MustInt16() int16

MustInt16 returns the value as int16. It panics if the value is not an int16.

func (*Entry[V]) MustInt32

func (e *Entry[V]) MustInt32() int32

MustInt32 returns the value as int32. It panics if the value is not an int32.

func (*Entry[V]) MustInt64

func (e *Entry[V]) MustInt64() int64

MustInt64 returns the value as int64. It panics if the value is not an int64.

func (*Entry[V]) MustRune

func (e *Entry[V]) MustRune() rune

MustRune returns the value as rune. It panics if the value is not a rune.

func (*Entry[V]) MustString

func (e *Entry[V]) MustString() string

MustString returns the value as string. It panics if the value is not a string.

func (*Entry[V]) MustStringSlice

func (e *Entry[V]) MustStringSlice() []string

MustStringSlice returns the value as []string. It panics if the value is not a []string.

func (*Entry[V]) MustTime

func (e *Entry[V]) MustTime() time.Time

MustTime returns the value as time.Time. It panics if the value is not a time.Time.

func (*Entry[V]) MustUUID

func (e *Entry[V]) MustUUID() uuid.UUID

MustUUID returns the value as uuid.UUID. It panics if the value is not a uuid.UUID.

func (*Entry[V]) MustUint

func (e *Entry[V]) MustUint() uint

MustUint returns the value as uint. It panics if the value is not a uint.

func (*Entry[V]) MustUint8

func (e *Entry[V]) MustUint8() uint8

MustUint8 returns the value as uint8. It panics if the value is not a uint8.

func (*Entry[V]) MustUint16

func (e *Entry[V]) MustUint16() uint16

MustUint16 returns the value as uint16. It panics if the value is not a uint16.

func (*Entry[V]) MustUint32

func (e *Entry[V]) MustUint32() uint32

MustUint32 returns the value as uint32. It panics if the value is not a uint32.

func (*Entry[V]) MustUint64

func (e *Entry[V]) MustUint64() uint64

MustUint64 returns the value as uint64. It panics if the value is not a uint64.

func (*Entry[V]) MustWeekday

func (e *Entry[V]) MustWeekday() time.Weekday

MustWeekday returns the value as time.Weekday. It panics if the value is not a time.Weekday.

func (Entry[V]) NotFound

func (e Entry[V]) NotFound(typ reflect.Type) *ErrEntryNotFound

NotFound is a helper function that returns a new ErrEntryNotFound. It's useful when you want to return a not found error from entries.

func (*Entry[V]) Rune

func (e *Entry[V]) Rune() rune

Rune returns the value as rune. A value stored as any other Go numeric is converted when it survives the conversion intact, and a numeric string is parsed. It returns 0 otherwise.

func (*Entry[V]) String

func (e *Entry[V]) String() string

String returns the value as string. It uses fmt.Sprintf to convert the value to string. Completes the fmt.Stringer interface.

func (*Entry[V]) StringSlice

func (e *Entry[V]) StringSlice() []string

StringSlice returns the value as []string. A string value is split by the entry's separator. It returns nil for any other type.

func (*Entry[V]) Time

func (e *Entry[V]) Time() time.Time

Time returns the value as time.Time, a point in time. A string value is passed through ParseTime (RFC 3339). The calendar-day layouts ("2006/01/02", "2006-01-02") belong to Date, not here. It returns the zero time.Time if the value is neither a time.Time nor a parsable string.

func (*Entry[V]) TrimFile

func (e *Entry[V]) TrimFile() string

TrimFile returns a value without the last ".ext" part.

func (*Entry[V]) TrimFileInt

func (e *Entry[V]) TrimFileInt() int

TrimFileInt same as TrimFile but it returns the value as int.

func (*Entry[V]) TrimHTML

func (e *Entry[V]) TrimHTML() string

TrimHTML returns a value without the last ".html" part. The extension is matched in any letter case.

func (*Entry[V]) TrimJSON

func (e *Entry[V]) TrimJSON() string

TrimJSON returns a value without the last ".json" part. The extension is matched in any letter case.

func (*Entry[V]) TrimXML

func (e *Entry[V]) TrimXML() string

TrimXML returns a value without the last ".xml" part. The extension is matched in any letter case.

func (*Entry[V]) UUID

func (e *Entry[V]) UUID() uuid.UUID

UUID returns the value as uuid.UUID. A string value is passed through uuid.Parse, which accepts the canonical hyphenated form, the braced and the urn:uuid: forms and the bare 32 hex digits, in any letter case. It returns the zero UUID (uuid.Nil()) if the value is neither a uuid.UUID nor a parsable string.

func (*Entry[V]) Uint

func (e *Entry[V]) Uint() uint

Uint returns the value as uint. A value stored as any other Go numeric is converted when it survives the conversion intact, and a numeric string is parsed. It returns 0 otherwise.

func (*Entry[V]) Uint8

func (e *Entry[V]) Uint8() uint8

Uint8 returns the value as uint8. A value stored as any other Go numeric is converted when it survives the conversion intact, and a numeric string is parsed. It returns 0 otherwise.

func (*Entry[V]) Uint16

func (e *Entry[V]) Uint16() uint16

Uint16 returns the value as uint16. A value stored as any other Go numeric is converted when it survives the conversion intact, and a numeric string is parsed. It returns 0 otherwise.

func (*Entry[V]) Uint32

func (e *Entry[V]) Uint32() uint32

Uint32 returns the value as uint32. A value stored as any other Go numeric is converted when it survives the conversion intact, and a numeric string is parsed. It returns 0 otherwise.

func (*Entry[V]) Uint64

func (e *Entry[V]) Uint64() uint64

Uint64 returns the value as uint64. A value stored as any other Go numeric is converted when it survives the conversion intact, and a numeric string is parsed. It returns 0 otherwise.

func (*Entry[V]) Weekday

func (e *Entry[V]) Weekday() time.Weekday

Weekday returns the value as time.Weekday. A string value is parsed by ParseWeekday. It returns -1 for any other type and for a string that does not parse.

type ErrEntryNotFound

type ErrEntryNotFound struct {
	Key  string       // the entry's key.
	Kind reflect.Kind // i.e bool, int, string...
	Type reflect.Type // i.e time.Time{} or custom struct.
}

ErrEntryNotFound may be returned from entry methods if a key (with a certain kind) was not found. Usage:

var e *ErrEntryNotFound errors.As(err, &e) To check for specific key error: errors.As(err, &e) && e.Key == "key" To check for specific key-kind error: errors.As(err, &e) && e.Key == "key" && e.Kind == reflect.Int

The target must always be a **ErrEntryNotFound (the address of a pointer variable); passing a struct literal makes errors.As panic, as the value type does not implement the error interface.

func (*ErrEntryNotFound) As

func (e *ErrEntryNotFound) As(target any) bool

As can be used to manually check if the error came from the entry is a not found entry, the key must much in order to return true. The target must be a *ErrEntryNotFound probe; its non-empty Key and its non-Invalid Kind must match this error's ones. Usage: e.As(&ErrEntryNotFound{Key: "key", Kind: reflect.Int})

Do NOT use this method directly, prefer` errors.As` method as explained above.

Implements: go/src/errors/wrap.go#84

func (*ErrEntryNotFound) Error

func (e *ErrEntryNotFound) Error() string

type FieldSetter

type FieldSetter[V any] func(field *reflect.StructField, ptr unsafe.Pointer, value V) error

FieldSetter is a function that sets a field value. It's used by the decoder to set the field value. The field is the reflect.StructField of the field. The ptr is a pointer to the field. The value is the value to set.

type FormDecoderOptions

type FormDecoderOptions = EntriesDecoderOptions[[]string]

FormDecoderOptions is the options for the form decoder. See `NewFormDecoder` package-level function for more.

type HeaderDecoderOptions

type HeaderDecoderOptions = EntriesDecoderOptions[[]string]

HeaderDecoderOptions is the options for the header decoder.

type KeyValuesDecoder

type KeyValuesDecoder[T any] struct {
	*EntriesDecoder[T, []string]
}

KeyValuesDecoder is a url query decoder. It decodes the url query to the target struct value of T. It is safe for concurrent use. See `NewKeyValuesDecoder` package-level function for more.

func NewFormDecoder

func NewFormDecoder[T any](opts FormDecoderOptions) (*KeyValuesDecoder[T], error)

NewFormDecoder returns a new form decoder. It returns an error if T is not a pointer to a struct. The options can be empty. See `FormDecoderOptions` struct and its `DecodeKeyValues` method for more.

func NewHeaderDecoder

func NewHeaderDecoder[T any](opts HeaderDecoderOptions) (*KeyValuesDecoder[T], error)

NewHeaderDecoder returns a new header decoder. It returns an error if T is not a pointer to a struct. The options can be empty. See `HeaderDecoderOptions` struct and its `DecodeKeyValues` method for more.

func NewKeyValuesDecoder

func NewKeyValuesDecoder[T any](opts KeyValuesDecoderOptions) (*KeyValuesDecoder[T], error)

NewKeyValuesDecoder returns a new url query decoder. It returns an error if T is not a pointer to a struct. The options can be empty. See `QueryDecoderOptions` struct and its `DecodeKeyValues` method for more.

func NewQueryDecoder

func NewQueryDecoder[T any](opts QueryDecoderOptions) (*KeyValuesDecoder[T], error)

NewQueryDecoder returns a new url query decoder. It returns an error if T is not a pointer to a struct. The options can be empty. See `QueryDecoderOptions` struct and its `DecodeKeyValues` method for more.

func (*KeyValuesDecoder[T]) DecodeKeyValues

func (d *KeyValuesDecoder[T]) DecodeKeyValues(query map[string][]string, target *T) error

DecodeKeyValues decodes the url query to the target struct value of T. Multiple values using the same key e.g. names=makis&names=george.

type KeyValuesDecoderOptions

type KeyValuesDecoderOptions = EntriesDecoderOptions[[]string]

KeyValuesDecoderOptions is the options for the url query decoder. See `NewKeyValuesDecoder` package-level function for more.

type PathParams

type PathParams = Entries[any] // no pointer to Param, as they are small and we don't want to allocate memory for each of them.

PathParams is a slice of Param. Empty if the route is static. It's used by the router to store the dynamic path parameters.

type PathParamsDecoderOptions

type PathParamsDecoderOptions = EntriesDecoderOptions[any]

PathParamsDecoderOptions is the options for the path params decoder.

type QueryDecoderOptions

type QueryDecoderOptions = EntriesDecoderOptions[[]string]

QueryDecoderOptions is the options for the url query decoder. See `NewQueryDecoder` package-level function for more.

type StringEntries

type StringEntries = Entries[string]

StringEntries is a slice of key-value pairs with string key and string value.

type StringEntry

type StringEntry = Entry[string]

StringEntry is a key-value pair with string key and string value.

type StringSliceEntries

type StringSliceEntries struct {
	StringEntries `json:"entries" yaml:"Entries" toml:"Entries" ini:"entries" env:"entries"` // no pointer, leave it read-only as it is used for request values and we also want to reest it without affecting the original values or having to nil the values.
	// contains filtered or unexported fields
}

StringSliceEntries is a read-only map[string][]string. It is used to represent a map[string][]string in a sorted and safe way. It contains a lot of helper methods to convert each value. It is used to represent URL query parameters or headers or form data.

func NewStringSliceEntries

func NewStringSliceEntries(m map[string][]string, valuesJoinSeparator string) StringSliceEntries

NewStringSliceEntries returns a new sorted StringSliceEntries. It converts each of the map values to a single string using the valuesJoinSeparator. The valuesJoinSeparator is used to join the values of the map. The same separator is used on StringSlice afterwards to get back the slice value. If valuesJoinSeparator is empty, "," is used.

func (StringSliceEntries) Exists

func (e StringSliceEntries) Exists(key string) bool

Exists returns true if the key exists in the original map.

func (StringSliceEntries) GetSeparator

func (e StringSliceEntries) GetSeparator() string

GetSeparator returns the separator used to join values in the map.

func (StringSliceEntries) GetSimpleDate

func (e StringSliceEntries) GetSimpleDate(keys ...string) (types.SimpleDate, bool, error)

GetSimpleDate returns the first non-empty value of the given keys parsed as a types.SimpleDate ("2006-01-02", or "2006-1-2"). Keys are tried in order and default to "date" when none is given; a value is trimmed and a blank one counts as absent.

It reports whether any key was present: a missing key returns (zero, false, nil) so the caller decides the default (today, an error, no filter), and an unparsable value returns (zero, true, err) so a client typo is not mistaken for an absent parameter. It renders nothing; the caller writes the response.

date, found, err := ctx.Query().GetSimpleDate("date", "day")
if err != nil {
	errors.InvalidArgument.Detailf(ctx, "invalid date query parameter", "%v", err)
	return
}
if !found {
	date = types.SimpleDateFromTime(time.Now().UTC())
}

func (StringSliceEntries) GetSlice

func (e StringSliceEntries) GetSlice(key string) []string

GetSlice returns the slice of values of a key from the original map.

func (StringSliceEntries) IsEmpty

func (e StringSliceEntries) IsEmpty() bool

IsEmpty returns true if the original map is empty.

func (StringSliceEntries) ToHeader

func (e StringSliceEntries) ToHeader() http.Header

ToHeader returns the original map as http.Header.

func (StringSliceEntries) ToMap

func (e StringSliceEntries) ToMap() map[string][]string

ToMap returns the original map.

func (StringSliceEntries) ToQuery

func (e StringSliceEntries) ToQuery() url.Values

ToQuery returns the original map as url.Values.

type StructValidator

type StructValidator interface {
	Validate() error
}

StructValidator is the interface that wraps the Validate method. Validate validates the struct value. It returns an error if the struct value is invalid. The error can be a *ValidationError.

Use this interface to validate the struct value after decoding the context values or path params or query or header or form data. The struct value must implement this interface to be validated, otherwise, the decoder will fallback to the "required" struct field option.

type ValidationError

type ValidationError struct {
	Field  string `json:"field,omitempty"`
	Value  any    `json:"value,omitempty"`
	Reason string `json:"reason"`
}

func (*ValidationError) Error

func (e *ValidationError) Error() string

Error implements the standard error interface.

func (*ValidationError) GetReason

func (e *ValidationError) GetReason() string

GetReason implements the rest/validation error interface.

func (*ValidationError) IsExtra

func (e *ValidationError) IsExtra() bool

IsExtra reports whether the error is an extra field error.

func (*ValidationError) IsRequired

func (e *ValidationError) IsRequired() bool

IsRequired reports whether the error is a required field error.

Jump to

Keyboard shortcuts

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