-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
54 lines (44 loc) · 926 Bytes
/
server.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
package main
import (
"context"
"net"
"sync"
log "github.com/sirupsen/logrus"
)
func StartTCPServer(ctx context.Context, wg *sync.WaitGroup, addr string, handler func(net.Conn)) {
defer wg.Done()
lc := net.ListenConfig{
KeepAlive: -1,
}
listener, err := lc.Listen(ctx, "tcp", addr)
if err != nil {
log.WithError(err).Error("Error creating listener")
return
}
defer listener.Close()
go func() {
<-ctx.Done()
listener.Close()
}()
log.Info("Server started on ", addr)
for {
conn, err := listener.Accept()
if err != nil {
if ctx.Err() != nil {
log.Info("Server stopped on port ", addr)
return
}
log.WithError(err).Error("Error accepting connection")
continue
}
go func() {
defer func() {
log.Debug("Closing connection")
if err := conn.Close(); err != nil {
log.WithError(err).Error("Error closing connection")
}
}()
handler(conn)
}()
}
}