-
Notifications
You must be signed in to change notification settings - Fork 12
/
main.go
97 lines (81 loc) · 2.21 KB
/
main.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package main
import (
"bufio"
"flag"
"fmt"
"os"
"strings"
"sync"
"github.com/gautamrege/gochat/api"
)
const helpStr = `Commands
1. /users :- Get list of live users
2. @{user} message :- send message to specified user
3. /exit :- Exit the Chat
4. /all :- Send message to all the users [TODO]`
var (
name = flag.String("name", "", "The name you want to chat as")
port = flag.Int("port", 12345, "Port that your server will run on.")
host = flag.String("host", "", "Host IP that your server is running on.")
preload = flag.Bool("preload", false, "Preload users from users.json")
stdReader = bufio.NewReader(os.Stdin)
)
var MyHandle api.Handle
var USERS = PeerHandleMapSync{
PeerHandleMap: make(map[string]api.Handle),
}
func main() {
// Parse flags for host, port and name
flag.Parse()
// TODO-WORKSHOP-STEP-1: If the name and host are empty, return an error with help message
// TODO-WORKSHOP-STEP-2: Initialize global MyHandle of type api.Handle
var wg sync.WaitGroup
wg.Add(3)
if *preload {
preloadUsers()
} else {
// Broadcast for is-alive on 33333 with own UserHandle.
go broadcastOwnHandle(&wg)
// Listener for is-alive broadcasts from other hosts. Listening on 33333
go listenAndRegisterUsers(&wg)
}
// gRPC listener
go startServer(&wg)
for {
fmt.Printf("> ")
textInput, _ := stdReader.ReadString('\n')
// convert CRLF to LF
textInput = strings.Replace(textInput, "\n", "", -1)
parseAndExecInput(textInput)
}
wg.Wait()
}
// Handle the input chat messages as well as help commands
func parseAndExecInput(input string) {
// Split the line into 2 tokens (cmd and message)
tokens := strings.SplitN(input, " ", 2)
cmd := tokens[0]
switch {
case cmd == "":
break
case cmd == "?":
fmt.Printf(helpStr)
break
case strings.ToLower(cmd) == "/users":
fmt.Println(USERS)
break
case strings.ToLower(cmd) == "/exit":
os.Exit(1)
break
case cmd[0] == '@':
// TODO-WORKSHOP-STEP-9: Write code to sendChat. Example
// "@gautam hello golang" should send a message to handle with name "gautam" and message "hello golang"
// Invoke sendChat to send the message
break
case strings.ToLower(cmd) == "/help":
fmt.Println(helpStr)
break
default:
fmt.Println(helpStr)
}
}