forked from gjbae1212/fluent-bit-pubsub
-
Notifications
You must be signed in to change notification settings - Fork 0
/
formats.go
65 lines (58 loc) · 1.25 KB
/
formats.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
package main
import (
"encoding/json"
"fmt"
)
type Formatter struct {
Encode func(interface{}) ([]byte, error)
}
var supportFormats = map[string]Formatter{
"json": {Encode: encodeToJSON},
}
func convertKeysToString(m map[interface{}]interface{}) map[string]interface{} {
nm := make(map[string]interface{})
for k, v := range m {
sk, ok := k.(string)
if !ok {
return nil
}
switch sv := v.(type) {
case map[interface{}]interface{}:
nm[sk] = convertKeysToString(sv)
case []interface{}:
nm[sk] = convertNestedSlice(sv)
case []byte:
nm[sk] = string(sv)
default:
nm[sk] = sv
}
}
return nm
}
func convertNestedSlice(s []interface{}) []interface{} {
ns := make([]interface{}, len(s))
for i, v := range s {
switch sv := v.(type) {
case map[interface{}]interface{}:
ns[i] = convertKeysToString(sv)
case []interface{}:
ns[i] = convertNestedSlice(sv)
case []byte:
ns[i] = string(sv)
default:
ns[i] = sv
}
}
return ns
}
func encodeToJSON(v interface{}) ([]byte, error) {
m, ok := v.(map[interface{}]interface{})
if !ok {
return nil, fmt.Errorf("invalid type, got %sv", v)
}
payload := convertKeysToString(m)
if payload == nil {
return nil, fmt.Errorf("invalid key type")
}
return json.Marshal(payload)
}