forked from gookit/goutil
-
Notifications
You must be signed in to change notification settings - Fork 0
/
wrapper.go
77 lines (63 loc) · 1.59 KB
/
wrapper.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package structs
import (
"errors"
"reflect"
)
// Wrapper struct for read or set field value
type Wrapper struct {
// src any // source struct
// reflect.Value of source struct
rv reflect.Value
// FieldTagName field name for read/write value. default tag: json
FieldTagName string
// caches for field rv and name and tag name TODO
fieldNames []string //lint:ignore U1000 for unused
fvCacheMap map[string]reflect.Value //lint:ignore U1000 for unused
}
// Wrap create a struct wrapper
func Wrap(src any) *Wrapper {
return NewWrapper(src)
}
// NewWrapper create a struct wrapper
func NewWrapper(src any) *Wrapper {
return WrapValue(reflect.ValueOf(src))
}
// WrapValue create a struct wrapper
func WrapValue(rv reflect.Value) *Wrapper {
rv = reflect.Indirect(rv)
if rv.Kind() != reflect.Struct {
panic("must be provider an struct value")
}
return &Wrapper{rv: rv}
}
// Get field value by name, name allow use dot syntax.
func (r *Wrapper) Get(name string) any {
val, ok := r.Lookup(name)
if !ok {
return nil
}
return val
}
// Lookup field value by name, name allow use dot syntax.
func (r *Wrapper) Lookup(name string) (val any, ok bool) {
fv := r.rv.FieldByName(name)
if !fv.IsValid() {
return
}
if fv.CanInterface() {
return fv.Interface(), true
}
return
}
// Set field value by name, name allow use dot syntax.
func (r *Wrapper) Set(name string, val any) error {
fv := r.rv.FieldByName(name)
if !fv.IsValid() {
return errors.New("field not found")
}
if !fv.CanSet() {
return errors.New("field can not set value")
}
fv.Set(reflect.ValueOf(val))
return nil
}