-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
101 lines (86 loc) · 2.45 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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package byor
import (
"errors"
"fmt"
"io"
"net"
"os"
"syscall"
terminal "golang.org/x/term"
)
func Client(port string) error {
addr, addrErr := net.ResolveTCPAddr("tcp", port)
if addrErr != nil {
return addrErr
}
tcpConn, connErr := net.DialTCP("tcp", nil, addr)
if connErr != nil {
return connErr
}
defer tcpConn.Close()
oldState, termErr := terminal.MakeRaw(int(os.Stdin.Fd()))
if termErr != nil {
return termErr
}
defer terminal.Restore(int(os.Stdin.Fd()), oldState)
screen := struct {
io.Reader
io.Writer
}{os.Stdin, os.Stdout}
term := terminal.NewTerminal(screen, "")
term.SetPrompt(string(term.Escape.Green) + "> " + string(term.Escape.Reset))
welcomeMessage := formatOutput(term, "Connected to Server at address - "+port)
fmt.Fprintln(term, welcomeMessage)
cmdHelp := formatOutput(term, "To exit prompt use command (ctrl+c)")
fmt.Fprintln(term, cmdHelp)
for {
line, rErr := term.ReadLine()
if rErr != nil {
if rErr == io.EOF {
return nil
}
return rErr
}
cmds, cmdsErr := composeReq(line)
if cmdsErr != nil {
fmt.Fprintln(term, formatErrorOutput(term, fmt.Sprintf("Parsing commands: %v", cmdsErr)))
continue
}
if wErr := Encoder(tcpConn, cmds); wErr != nil {
if errors.Is(wErr, syscall.EPIPE) {
return wErr
}
fmt.Fprintln(term, formatErrorOutput(term, fmt.Sprintf("Writing to server: %v", wErr)))
continue
}
data, dataErr := Decoder(tcpConn)
if dataErr != nil {
if errors.Is(dataErr, io.EOF) {
return dataErr
}
fmt.Fprintln(term, formatErrorOutput(term, fmt.Sprintf("Reading from server: %v", dataErr)))
continue
}
code, resStrs := responseHandler(data)
if code == RES_ERR || code == RES_NX {
for i := 0; i < len(resStrs); i += 1 {
fmt.Fprintln(term, formatErrorOutput(term, resStrs[i]))
}
} else if code == RES_OK {
for i := 0; i < len(resStrs); i += 1 {
fmt.Fprintln(term, formatServerReply(term, resStrs[i]))
}
} else {
fmt.Fprintln(term, formatErrorOutput(term, "Invalid server response code"))
}
}
}
func formatOutput(term *terminal.Terminal, str string) string {
return string(term.Escape.Cyan) + "# " + str + string(term.Escape.Reset)
}
func formatServerReply(term *terminal.Terminal, str string) string {
return string(term.Escape.Yellow) + "[REPLY] " + str + string(term.Escape.Reset)
}
func formatErrorOutput(term *terminal.Terminal, err string) string {
return string(term.Escape.Red) + "[ERROR] " + err + string(term.Escape.Reset)
}