-
Notifications
You must be signed in to change notification settings - Fork 17
/
gowschat.go
73 lines (61 loc) · 1.7 KB
/
gowschat.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
package machat
import (
"fmt"
"log"
"net/http"
"github.com/minaandrawos/machat/chatapi"
"github.com/gorilla/websocket"
)
type websocketConnWrapper struct {
*websocket.Conn
msgType int
}
func (wsWrapper *websocketConnWrapper) Read(b []byte) (int, error) {
t, r, err := wsWrapper.NextReader()
wsWrapper.msgType = t
if err != nil {
log.Println("Websocket err:", err)
return 0, err
}
return r.Read(b)
}
func (wsWrapper *websocketConnWrapper) Write(p []byte) (int, error) {
err := wsWrapper.WriteMessage(wsWrapper.msgType, p)
if err != nil {
return 0, err
}
return len(p), nil
}
func (wsWrapper *websocketConnWrapper) Close() error {
return wsWrapper.Conn.Close()
}
type wsChatHandler struct {
*websocket.Upgrader
*chatapi.ChatAPI
}
//RunWSChatWithExistingAPI starts a websocket chat server with an existing chat api session
func RunWSChatWithExistingAPI(url, address string, Rbsize, Wbsize int, chat *chatapi.ChatAPI) error {
wsHandler := &wsChatHandler{
Upgrader: &websocket.Upgrader{
ReadBufferSize: Rbsize,
WriteBufferSize: Wbsize,
},
ChatAPI: chat,
}
http.HandleFunc(url, wsHandler.wshandler)
return http.ListenAndServe(address, nil)
}
//RunWSChat starts a websocket chat server
func RunWSChat(url, address string, Rbsize, Wbsize int) error {
return RunWSChatWithExistingAPI(url, address, Rbsize, Wbsize, chatapi.New())
}
func (wh *wsChatHandler) wshandler(w http.ResponseWriter, r *http.Request) {
conn, err := wh.Upgrade(w, r, nil)
if err != nil {
log.Println("Error occured while trying to upgrade websocket", err)
fmt.Fprintf(w, "Error occured while trying to upgrade websocket: %v", err)
return
}
wsWrapper := &websocketConnWrapper{Conn: conn}
wh.AddClient(wsWrapper)
}