-
Notifications
You must be signed in to change notification settings - Fork 0
/
admin.go
76 lines (64 loc) · 1.25 KB
/
admin.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
package main
import (
"net"
"log"
"bufio"
"io"
"strings"
)
func (f *FS) TextCommand(cmd string) (string, error) {
switch strings.ToUpper(cmd) {
case "PING":
return "PONG", nil
}
return "commands: HELP PING", nil
}
func (f *FS) SpawnAdminConsole() error {
listen, err := net.Listen("tcp", "localhost:2000")
if err != nil {
return err
}
go func() {
for {
conn, err := listen.Accept()
if err != nil {
log.Println("admin console accept error:", err)
} else {
go handleAdmin(f, conn)
}
}
}()
return nil
}
func handleAdmin(f *FS, conn net.Conn) {
defer conn.Close()
log.Println("admin console opened")
reader := bufio.NewReader(conn)
writer := bufio.NewWriter(conn)
for {
line, err := reader.ReadString('\n')
if err == io.EOF {
log.Println("admin console closed")
return
}
if err != nil {
log.Println("admin console read error:", err)
return
}
line = strings.Trim(line, "\n\r\t ")
resp, err := f.TextCommand(line)
if err != nil {
resp = err.Error()
}
_, err = writer.WriteString(resp + "\n")
if err != nil {
log.Println("admin console write error:", err)
return
}
err = writer.Flush()
if err != nil {
log.Println("admin console write flush error:", err)
return
}
}
}