-
Notifications
You must be signed in to change notification settings - Fork 141
/
mq.go
80 lines (61 loc) · 1.38 KB
/
mq.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 lhttp
import (
"io/ioutil"
"log"
"net/http"
"strings"
"github.com/nats-io/nats"
)
type MqHandler interface{}
type Mq struct {
conn *nats.EncodedConn
}
func (mq *Mq) Publish(key string, v MqHandler) error {
return mq.conn.Publish(key, v)
}
func (mq *Mq) Subscribe(key string, v MqHandler) (*nats.Subscription, error) {
return mq.conn.Subscribe(key, v)
}
/*
func (mq *Mq) Unsubscribe(sub *nats.Subscription) error {
return sub.Unsubscribe()
}
*/
func (mq *Mq) Unsubscribe(handle interface{}) error {
c :=handle.(*nats.Subscription)
return c.Unsubscribe()
}
var mq Mq
func NewMq() *Mq {
return &mq
}
type httpPublisher struct{}
func (*httpPublisher) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
body, err := ioutil.ReadAll(req.Body)
if err != nil {
log.Print("an error occur")
}
log.Print("http publish body: ", string(body))
bodyStr := string(body)
message := buildMessage(bodyStr)
channels, ok := message.headers[HEADER_KEY_PUBLISH]
if !ok {
log.Print("cant get Publish header")
return
}
for _, c := range strings.Split(channels, " ") {
mq.Publish(c, bodyStr)
}
req.Body.Close()
}
func init() {
nc, _ := nats.Connect(nats.DefaultURL)
c, err := nats.NewEncodedConn(nc, nats.DEFAULT_ENCODER)
if err != nil {
log.Print("mq init error")
} else {
mq.conn = c
}
//handle http publish message
http.Handle("/publish", &httpPublisher{})
}