-
Notifications
You must be signed in to change notification settings - Fork 24
/
message.go
51 lines (46 loc) · 949 Bytes
/
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
package main
import (
"encoding/json"
msgpack "github.com/vmihailenco/msgpack"
"strconv"
"strings"
)
type Message struct {
Topic string
Payload []byte
Values []string
Keys []float64
}
func MsgParse(payload []byte) (map[string]interface{}, error) {
var j map[string]interface{}
// first, try msgpack
err := msgpack.Unmarshal(payload, &j)
if err != nil {
// next, try json
err := json.Unmarshal(payload, &j)
if err != nil {
// try plain numbers
s := string(payload)
if strings.Contains(s, ".") {
value, err := strconv.ParseFloat(s, 64)
if err == nil {
j = map[string]interface{}{"value": value}
} else {
return j, err
}
} else {
value, err := strconv.ParseInt(s, 10, 64)
if err == nil {
j = map[string]interface{}{"value": value}
}else {
return j, err
}
}
}
}
if _, ok := j["time"]; ok {
j["_time"] = j["time"]
delete(j, "time")
}
return j, nil
}