-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathmessage.go
80 lines (70 loc) · 1.73 KB
/
message.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
package wsqueue
import (
"encoding/json"
"os"
"reflect"
"strconv"
"time"
"github.com/satori/go.uuid"
)
type Header map[string]string
//Message message
type Message struct {
Header Header `json:"metadata,omitempty"`
Body string `json:"data"`
}
func newMessage(data interface{}) (*Message, error) {
m := Message{
Header: make(map[string]string),
Body: "",
}
switch data.(type) {
case string, *string:
m.Header["content-type"] = "string"
m.Body = data.(string)
case int, *int, int32, *int32, int64, *int64:
m.Header["content-type"] = "int"
m.Body = strconv.Itoa(data.(int))
case bool, *bool:
m.Header["content-type"] = "bool"
m.Body = strconv.FormatBool(data.(bool))
default:
m.Header["content-type"] = "application/json"
if reflect.TypeOf(data).Kind() == reflect.Ptr {
m.Header["application-type"] = reflect.ValueOf(data).Elem().Type().String()
} else {
m.Header["application-type"] = reflect.ValueOf(data).Type().String()
}
b, err := json.Marshal(data)
if err != nil {
return nil, err
}
m.Body = string(b)
}
m.Header["id"] = uuid.NewV1().String()
m.Header["date"] = time.Now().String()
m.Header["host"], _ = os.Hostname()
return &m, nil
}
func (m *Message) String() string {
var s string
s = "\n---HEADER---"
for k, v := range m.Header {
s = s + "\n" + k + ":" + v
}
s = s + "\n---BODY---"
s = s + "\n" + m.Body
return s
}
//ID returns message if
func (m *Message) ID() string {
return m.Header["id"]
}
//ContentType returns content-type
func (m *Message) ContentType() string {
return m.Header["content-type"]
}
//ApplicationType returns application-type. Empty if content-type is not application/json
func (m *Message) ApplicationType() string {
return m.Header["application-type"]
}