This repository has been archived by the owner on Aug 27, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 27
/
result.go
72 lines (63 loc) · 1.47 KB
/
result.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
// Copyright (c) 2017-2018 The qitmeer developers
package json
import (
"bytes"
"encoding/json"
"reflect"
)
// The Result works as method calling response can be marshaled as json map
type Result map[string]interface{}
// The OrderedResult works as the order map[string]interface{}, which useful to
// marshal a Json map using a specific order
// Note:
// it works almost as the 'omitEmpty' set to true, empty value should be omitted when marshaling.
// only for empty string/array/map/slice/interface
type OrderedResult []KV
type KV struct {
Key string
Val interface{}
}
func (ores OrderedResult) MarshalJSON() ([]byte, error) {
var buf bytes.Buffer
buf.WriteString("{")
for i, kv := range ores {
if isEmptyValue(reflect.ValueOf(kv.Val)) {
continue //omit empty
}
if i != 0 {
buf.WriteString(",")
}
// marshal key
key, err := json.Marshal(kv.Key)
if err != nil {
return nil, err
}
buf.Write(key)
buf.WriteString(":")
// marshal value
val, err := json.Marshal(kv.Val)
if err != nil {
return nil, err
}
buf.Write(val)
}
buf.WriteString("}")
return buf.Bytes(), nil
}
func (ores *OrderedResult) GetValue(key string) interface{} {
for _, kv := range *ores {
if kv.Key == key {
return kv.Val
}
}
return nil
}
func isEmptyValue(v reflect.Value) bool {
switch v.Kind() {
case reflect.Array, reflect.Map, reflect.Slice, reflect.String:
return v.Len() == 0
case reflect.Interface, reflect.Ptr:
return v.IsNil()
}
return false
}