/
topic.go
76 lines (60 loc) · 1.39 KB
/
topic.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
package main
import (
"encoding/json"
"github.com/asdine/lobby"
"github.com/pkg/errors"
mgo "gopkg.in/mgo.v2"
)
const colMessages = "messages"
type message struct {
ID string `bson:"_id,omitempty"`
Topic string `bson:"topic"`
Group string `bson:"group"`
Value interface{} `bson:"value"`
}
var _ lobby.Topic = new(Topic)
// NewTopic returns a MongoDB Topic.
func NewTopic(session *mgo.Session, name string) *Topic {
return &Topic{
session: session,
name: name,
}
}
// Topic is a MongoDB implementation of a topic.
type Topic struct {
session *mgo.Session
name string
}
// Send a message to the topic.
func (t *Topic) Send(m *lobby.Message) error {
col := t.session.DB("").C(colMessages)
var raw interface{}
valid, err := ValidateBytes(m.Value)
if err == nil {
err := json.Unmarshal(valid, &raw)
if err != nil {
return errors.Wrap(err, "failed to unmarshal json")
}
} else {
raw = m.Value
}
err = col.Insert(&message{Group: m.Group, Topic: t.name, Value: raw})
if err != nil {
return errors.Wrap(err, "failed to insert of update")
}
return nil
}
// Close the topic session.
func (t *Topic) Close() error {
t.session.Close()
return nil
}
// ValidateBytes checks if the data is valid json.
func ValidateBytes(data []byte) ([]byte, error) {
var i json.RawMessage
err := json.Unmarshal(data, &i)
if err != nil {
return nil, err
}
return i, nil
}