-
Notifications
You must be signed in to change notification settings - Fork 36
/
msg.go
93 lines (76 loc) · 1.8 KB
/
msg.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
84
85
86
87
88
89
90
91
92
93
package workers
import (
"log"
"os"
"reflect"
"github.com/bitly/go-simplejson"
)
// Logger is the default go-workers2 logger, only used here in this file.
// TODO: remove this
var Logger = log.New(os.Stdout, "go-workers2: ", log.Ldate|log.Lmicroseconds)
type data struct {
*simplejson.Json
}
// Msg is the struct for job data (parameters and metadata)
type Msg struct {
*data
original string
ack bool
startedAt int64
}
// Args is the set of parameters for a message
type Args struct {
*data
}
// Class returns class attribute of a message
func (m *Msg) Class() string {
return m.Get("class").MustString()
}
// Jid returns job id attribute of a message
func (m *Msg) Jid() string {
return m.Get("jid").MustString()
}
// Args returns arguments attribute of a message
func (m *Msg) Args() *Args {
if args, ok := m.CheckGet("args"); ok {
return &Args{&data{args}}
}
d, _ := newData("[]")
return &Args{d}
}
// OriginalJson returns the original JSON message
func (m *Msg) OriginalJson() string {
return m.original
}
// ToJson return data in JSON format th message
func (d *data) ToJson() string {
json, err := d.Encode()
if err != nil {
Logger.Println("ERR: Couldn't generate json from", d, ":", err)
}
return string(json)
}
func (d *data) Equals(other interface{}) bool {
otherJSON := reflect.ValueOf(other).MethodByName("ToJson").Call([]reflect.Value{})
return d.ToJson() == otherJSON[0].String()
}
// NewMsg returns a new message
func NewMsg(content string) (*Msg, error) {
d, err := newData(content)
if err != nil {
return nil, err
}
return &Msg{
data: d,
original: content,
ack: true,
startedAt: 0,
}, nil
}
func newData(content string) (*data, error) {
json, err := simplejson.NewJson([]byte(content))
if err != nil {
return nil, err
}
return &data{json}, nil
}