-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
68 lines (54 loc) · 1.23 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
package main
import (
"bufio"
"net"
"sync"
"github.com/google/uuid"
"go.uber.org/zap"
)
func main() {
var loggerConfig = zap.NewProductionConfig()
loggerConfig.Level.SetLevel(zap.DebugLevel)
logger, err := loggerConfig.Build()
if err != nil {
panic(err)
}
l, err := net.Listen("tcp", "localhost:9090")
if err != nil {
return
}
defer l.Close()
// Using sync.Map to not deal with concurrency slice/map issues
var connMap = &sync.Map{}
for {
conn, err := l.Accept()
if err != nil {
logger.Error("error accepting connection", zap.Error(err))
return
}
id := uuid.New().String()
connMap.Store(id, conn)
go handleUserConnection(id, conn, connMap, logger)
}
}
func handleUserConnection(id string, c net.Conn, connMap *sync.Map, logger *zap.Logger) {
defer func() {
c.Close()
connMap.Delete(id)
}()
for {
userInput, err := bufio.NewReader(c).ReadString('\n')
if err != nil {
logger.Error("error reading from client", zap.Error(err))
return
}
connMap.Range(func(key, value interface{}) bool {
if conn, ok := value.(net.Conn); ok {
if _, err := conn.Write([]byte(userInput)); err != nil {
logger.Error("error accepting connection", zap.Error(err))
}
}
return true
})
}
}