-
Notifications
You must be signed in to change notification settings - Fork 0
/
chat.go
79 lines (71 loc) · 1.55 KB
/
chat.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
package chat
import (
"fmt"
"log"
"net/http"
"time"
"github.com/gorilla/websocket"
"github.com/micro/go-micro/broker"
"github.com/micro/go-micro/registry"
)
var (
DefaultName = "go-chat"
DefaultVersion = "latest"
DefaultTopic = "go.micro.web.chat"
upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool {
return true
},
}
)
type service struct {
hub *Hub
broker *Broker
}
func NewService() *service {
return &service{
hub: NewHub(),
}
}
func (s *service) Init(opts ...Option) error {
o := newOptions(opts...)
// key
chatKeyPrefix := fmt.Sprintf("%s:%s:", o.Name, o.Version)
appKeyPrefix := chatKeyPrefix + "app:"
// broker
s.broker = NewBroker(
o.Topic,
newQueue(chatKeyPrefix, appKeyPrefix, o.RedisOptions),
broker.Registry(
registry.NewRegistry(o.RegistryOptions...),
),
)
return nil
}
func (s *service) Run() error {
if err := s.broker.Init(); err != nil {
return err
}
go s.hub.Run()
go s.hub.Clean()
go s.broker.Subscribe(s.hub)
return nil
}
// NewHandler handles websocket requests from the peer.
func (s *service) NewHandler() func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Println(err)
return
}
defer conn.Close()
client := &Client{broker: s.broker, hub: s.hub, conn: conn, send: make(chan []byte, 256)}
client.time = time.Now()
client.hub.register <- client
go client.writer()
client.reader()
}
}