/
json_message_formatter.go
60 lines (50 loc) · 1.55 KB
/
json_message_formatter.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
// Copyright (C) 2017 Jan Delgado
package main
import (
"encoding/json"
"strings"
rabtap "github.com/jandelgado/rabtap/pkg"
)
// JSONMessageFormatter pretty prints JSON formatted messages.
type JSONMessageFormatter struct{}
var (
_ = func() struct{} {
RegisterMessageFormatter("application/json", JSONMessageFormatter{})
return struct{}{}
}()
)
// Format tries to format a message in JSON format. The body can be a simple
// JSON object or an array of JSON objects. If the message is not valid JSON,
// it will be returned unformatted as-is.
func (s JSONMessageFormatter) Format(message rabtap.TapMessage) string {
var formatted []byte
originalMessage := strings.TrimSpace(string(message.AmqpMessage.Body))
if len(originalMessage) == 0 {
return string(message.AmqpMessage.Body)
}
if originalMessage[0] == '[' {
// try to unmarshal array to JSON objects
var arrayJSONObj []map[string]interface{}
err := json.Unmarshal([]byte(originalMessage), &arrayJSONObj)
if err != nil {
return string(message.AmqpMessage.Body)
}
// pretty print JSON
formatted, err = json.MarshalIndent(arrayJSONObj, "", " ")
if err != nil {
return string(message.AmqpMessage.Body)
}
} else {
// try to unmarshal simple json object
var simpleJSONObj map[string]interface{}
err := json.Unmarshal([]byte(originalMessage), &simpleJSONObj)
if err != nil {
return string(message.AmqpMessage.Body)
}
formatted, err = json.MarshalIndent(simpleJSONObj, "", " ")
if err != nil {
return string(message.AmqpMessage.Body)
}
}
return string(formatted)
}