-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
78 lines (67 loc) · 1.34 KB
/
client.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
package main
import (
"bufio"
"fmt"
"net"
"strings"
"cloud.google.com/go/firestore"
"google.golang.org/api/iterator"
)
type client struct {
conn net.Conn
name string
commands chan<- command
}
func (c *client) inputReader() {
for {
msg, err := bufio.NewReader(c.conn).ReadString('\n')
if err != nil {
return
}
msg = strings.Trim(msg, "\r\n")
args := strings.Split(msg, " ")
cmd := strings.TrimSpace(args[0])
switch cmd {
case "/users":
c.commands <- command{
id: CMD_USERS,
client: c,
args: args,
}
case "/msg":
c.commands <- command{
id: CMD_MSG,
client: c,
args: args,
}
case "/quit":
c.commands <- command{
id: CMD_QUIT,
client: c,
args: args,
}
default:
c.err(fmt.Errorf("unknown command %s", cmd))
}
}
}
func (c *client) err(err error) {
c.conn.Write([]byte("ERROR: " + err.Error() + "\n"))
}
func (c *client) showHist(s *server) {
iter := s.dbClient.Collection("chats").OrderBy("createdAt", firestore.Asc).Limit(100).Documents(*s.ctx)
for {
doc, err := iter.Next()
if err == iterator.Done {
break
} else if err != nil {
fmt.Println(err.Error())
break
}
msg := fmt.Sprintf("%v: %v", doc.Data()["name"], doc.Data()["text"])
c.msg(msg)
}
}
func (c *client) msg(msg string) {
c.conn.Write([]byte("> " + msg + "\n"))
}