structs

package
v0.3.1 Latest Latest
Warning

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

Go to latest
Published: May 2, 2025 License: MIT Imports: 9 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	WithTagHandlerValueMapping = func() TagHandlerOption {
		return func(t *TagParser) {
			t.SetHandler("mapping", func(ctx context.Context, content string, field reflect.StructField, value reflect.Value) {
				if field.Type.Kind() != reflect.Interface {
					g.Log().Warningf(ctx, "using mapping parser, field %s type is not interface", field.Name)
					return
				}
				if value.IsNil() || !value.CanSet() {
					return
				}
				v := GetFieldMappingValue(content, value.Interface())
				if v == nil {
					return
				}
				value.Set(reflect.ValueOf(v))
			})
		}
	}
	// WithTagHandlerDefaultVal set default value for field when value not zero,
	// supports type of string, int8/16/32/64, uint8/16/32/64, float32/64, bool.
	WithTagHandlerDefaultVal = func() TagHandlerOption {
		return func(t *TagParser) {
			t.SetHandler("default", func(ctx context.Context, content string, field reflect.StructField, value reflect.Value) {
				kind := field.Type.Kind()
				if !value.CanSet() || !value.IsZero() {
					return
				}
				switch kind {
				case reflect.String:
					value.SetString(content)
				case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
					value.SetInt(gconv.Int64(content))
				case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
					value.SetUint(gconv.Uint64(content))
				case reflect.Float32, reflect.Float64:
					value.SetFloat(gconv.Float64(content))
				case reflect.Bool:
					value.SetBool(gconv.Bool(content))
				default:
				}
			})
		}
	}
)

Functions

func GetFieldMappingValue

func GetFieldMappingValue(name string, key any, def ...any) (val any)

func LoadMappingFromEmbed

func LoadMappingFromEmbed(ctx context.Context, efs embed.FS) (err error)

func SetFieldMapping

func SetFieldMapping(name string, m map[any]any)

Types

type FieldMapping

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

type TagHandler

type TagHandler func(ctx context.Context, content string, field reflect.StructField, value reflect.Value)

type TagHandlerOption

type TagHandlerOption func(t *TagParser)

type TagParser

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

func NewTagParser

func NewTagParser(opts ...TagHandlerOption) *TagParser

func (*TagParser) Parse

func (p *TagParser) Parse(ctx context.Context, v any)

Parse struct fields by tag dfs set with SetHandler.

func (*TagParser) SetHandler

func (p *TagParser) SetHandler(tag string, handler TagHandler)

func (*TagParser) TryParse

func (p *TagParser) TryParse(ctx context.Context, v any)

Jump to

Keyboard shortcuts

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