forked from tangx/goenv
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmethod_caller.go
More file actions
49 lines (37 loc) · 833 Bytes
/
method_caller.go
File metadata and controls
49 lines (37 loc) · 833 Bytes
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
package envutils
import (
"fmt"
"reflect"
)
func methodCaller(rv reflect.Value, methods ...string) error {
if rv.Kind() != reflect.Ptr || rv.Elem().Kind() != reflect.Struct {
return fmt.Errorf("want a struct prt, got a %v of %v", rv.Kind(), rv.Elem().Kind())
}
// call Method: Init and SetDefaults
for _, method := range methods {
mv := rv.MethodByName(method)
if mv.IsValid() {
mv.Call(nil)
}
}
rv = reflect.Indirect(rv)
rt := rv.Type()
for i := 0; i < rv.NumField(); i++ {
fv := rv.Field(i)
ft := rt.Field(i)
tag, _ := ft.Tag.Lookup("env")
if tag == "-" {
continue
}
if !fv.CanInterface() {
continue
}
if fv.Kind() != reflect.Ptr || fv.Elem().Kind() != reflect.Struct {
continue
}
if err := methodCaller(fv, methods...); err != nil {
return err
}
}
return nil
}