-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.go
44 lines (38 loc) · 803 Bytes
/
api.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
package sg_api
import (
"fmt"
"github.com/google/uuid"
"github.com/gorilla/websocket"
"github.com/withmandala/go-log"
"os"
)
var logger = log.New(os.Stdout)
func Listen(w *WsConn, cb func(resp string)) error {
defer w.conn.Close()
for {
_, msg, err := w.conn.ReadMessage()
if err != nil {
logger.Warn(err)
return err
} else {
cb(string(msg))
}
}
}
func Send(w *WsConn, message string) error {
err := w.conn.WriteMessage(websocket.TextMessage, []byte(message))
if err != nil {
w.conn.Close()
return err
}
return nil
}
func New(i Instance, u uuid.UUID) (*WsConn, error) {
endpoint := fmt.Sprintf("%s/%s", i.Endpoint, u)
conn, _, err := websocket.DefaultDialer.Dial(endpoint, nil)
if err != nil { return nil, err }
return &WsConn{
conn: conn,
Id: u,
}, nil
}