@@ -12,27 +12,24 @@ import (
12
12
"go.coder.com/slog"
13
13
)
14
14
15
- // Reflector is implemented by a value passed to Field
16
- // that would like to only use the reflection based
17
- // converter for itself and ignore interfaces like error
18
- // or fmt.Stringer .
19
- type Reflector interface {
20
- LogWithReflect ( )
15
+ // Encode uses interface detection and reflection to Encode v into a
16
+ // Value that uses only the primitive value types defined in this package.
17
+ // Use Reflect if you'd like to force the value to be encoded with reflection and
18
+ // ignore other interfaces .
19
+ func Encode ( v interface {}) Value {
20
+ return encode ( reflect . ValueOf ( v ) )
21
21
}
22
22
23
- // Reflect uses reflection to convert the slice of fields into a ordered
24
- // map that uses only the primitive value types defined in this package.
25
- // It uses interfaces like error and fmt.Stringer where appropriate.
26
- // Have a type implement Reflector if you would like to force
27
- func Reflect (fs []slog.Field ) Map {
28
- var m Map
29
- for _ , f := range fs {
30
- m = m .appendVal (f .LogKey (), reflectValue (reflect .ValueOf (f .LogValue ())))
31
- }
32
- return m
23
+ // Reflect uses reflection to convert v to a Value.
24
+ // Nested values inside v will be converted using the
25
+ // Encode function which considers interfaces.
26
+ // You should use this inside a slog.Value to force
27
+ // reflection over fmt.Stringer and error.
28
+ func Reflect (v interface {}) Value {
29
+ return reflectValue (reflect .ValueOf (v ))
33
30
}
34
31
35
- func reflectValue (rv reflect.Value ) Value {
32
+ func encode (rv reflect.Value ) Value {
36
33
if ! rv .IsValid () {
37
34
// reflect.ValueOf(nil).IsValid == false
38
35
return nil
@@ -49,9 +46,6 @@ func reflectValue(rv reflect.Value) Value {
49
46
50
47
typ := rv .Type ()
51
48
switch {
52
- case implements (typ , (* Reflector )(nil )):
53
- // Skip checking for any other interfaces as the value wants
54
- //
55
49
case implements (typ , (* Value )(nil )):
56
50
v := rv .MethodByName ("isSlogCoreValue" ).Call (nil )
57
51
return v [0 ].Interface ().(Value )
@@ -76,13 +70,24 @@ func reflectValue(rv reflect.Value) Value {
76
70
return String (s [0 ].String ())
77
71
}
78
72
73
+ // Fallback to pure reflection.
74
+ return reflectValue (rv )
75
+ }
76
+
77
+ func reflectValue (rv reflect.Value ) Value {
78
+ if ! rv .IsValid () {
79
+ // reflect.ValueOf(nil).IsValid == false
80
+ return nil
81
+ }
82
+
79
83
switch rv .Kind () {
80
84
case reflect .Chan , reflect .Func , reflect .Interface , reflect .Map , reflect .Ptr , reflect .Slice :
81
85
if rv .IsNil () {
82
86
return nil
83
87
}
84
88
}
85
89
90
+ typ := rv .Type ()
86
91
switch rv .Kind () {
87
92
case reflect .String :
88
93
return String (rv .String ())
0 commit comments