MCPcopy Create free account
hub / github.com/coder/slog / encode

Function encode

map.go:73–120  ·  view source on GitHub ↗
(v interface{})

Source from the content-addressed store, hash-verified

71}
72
73func encode(v interface{}) []byte {
74 if vr, ok := v.(driver.Valuer); ok {
75 var err error
76 v, err = vr.Value()
77 if err != nil {
78 return encodeJSON(fmt.Sprintf("error calling Value: %v", err))
79 }
80 }
81
82 switch v := v.(type) {
83 case json.Marshaler:
84 return encodeJSON(v)
85 case xerrors.Formatter:
86 return encode(errorChain(v))
87 }
88
89 rv := reflect.Indirect(reflect.ValueOf(v))
90 if !rv.IsValid() {
91 return encodeJSON(v)
92 }
93
94 if rv.Kind() == reflect.Struct {
95 b, ok := encodeStruct(rv)
96 if ok {
97 return b
98 }
99 }
100
101 switch v.(type) {
102 case error, fmt.Stringer:
103 return encode(fmt.Sprint(v))
104 }
105
106 switch rv.Type().Kind() {
107 case reflect.Slice:
108 if !rv.IsNil() {
109 return marshalList(rv)
110 }
111 case reflect.Array:
112 return marshalList(rv)
113 case reflect.Struct, reflect.Chan, reflect.Complex64, reflect.Complex128, reflect.Func:
114 // These types cannot be directly encoded with json.Marshal.
115 // See https://golang.org/pkg/encoding/json/#Marshal
116 return encodeJSON(fmt.Sprintf("%+v", v))
117 }
118
119 return encodeJSON(v)
120}
121
122func encodeStruct(rv reflect.Value) ([]byte, bool) {
123 if rv.Kind() == reflect.Struct {

Callers 3

MarshalJSONMethod · 0.85
marshalListFunction · 0.85
encodeJSONFunction · 0.85

Calls 4

encodeJSONFunction · 0.85
errorChainFunction · 0.85
encodeStructFunction · 0.85
marshalListFunction · 0.85

Tested by

no test coverage detected