-
Notifications
You must be signed in to change notification settings - Fork 14
/
format_from_pretty_print.go
83 lines (64 loc) · 1.76 KB
/
format_from_pretty_print.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
73
74
75
76
77
78
79
80
81
82
83
package transform
import (
"bytes"
"context"
"encoding/json"
"fmt"
"github.com/brexhq/substation/config"
iconfig "github.com/brexhq/substation/internal/config"
"github.com/brexhq/substation/message"
)
const (
formatFromPPOpenCurlyBracket = 123 // {
formatFromPPCloseCurlyBracket = 125 // }
)
type formatFromPrettyPrintConfig struct{}
func (c *formatFromPrettyPrintConfig) Decode(in interface{}) error {
return iconfig.Decode(in, c)
}
func newFormatFromPrettyPrint(_ context.Context, cfg config.Config) (*formatFromPrettyPrint, error) {
conf := formatFromPrettyPrintConfig{}
if err := conf.Decode(cfg.Settings); err != nil {
return nil, fmt.Errorf("transform: format_from_pretty_print: %v", err)
}
tf := formatFromPrettyPrint{
conf: conf,
}
return &tf, nil
}
type formatFromPrettyPrint struct {
conf formatFromPrettyPrintConfig
count int
stack []byte
}
func (tf *formatFromPrettyPrint) Transform(ctx context.Context, msg *message.Message) ([]*message.Message, error) {
if msg.IsControl() {
return []*message.Message{msg}, nil
}
for _, data := range msg.Data() {
tf.stack = append(tf.stack, data)
if data == formatFromPPOpenCurlyBracket {
tf.count++
}
if data == formatFromPPCloseCurlyBracket {
tf.count--
}
if tf.count == 0 {
var buf bytes.Buffer
if err := json.Compact(&buf, tf.stack); err != nil {
return nil, fmt.Errorf("transform: format_from_pretty_print: json compact: %v", err)
}
tf.stack = []byte{}
if json.Valid(buf.Bytes()) {
msg.SetData(buf.Bytes())
return []*message.Message{msg}, nil
}
return nil, fmt.Errorf("transform: format_from_pretty_print: invalid json")
}
}
return nil, nil
}
func (tf *formatFromPrettyPrint) String() string {
b, _ := json.Marshal(tf.conf)
return string(b)
}