This repository has been archived by the owner on Jan 21, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
service.go
56 lines (51 loc) · 1.56 KB
/
service.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
package main
import (
"context"
"log"
"fmt"
"net"
)
type ConnHandler func(context.Context, net.Conn)
func handleConnections(ctx context.Context, listener net.Listener, handler ConnHandler) {
// Close the listener if the context is cancelled.
defer listener.Close()
go func() {
<-ctx.Done()
listener.Close()
}()
connId := 0
for {
conn, err := listener.Accept()
if err != nil && ctx.Err() == context.Canceled {
// We failed to accept a connection because we shutting down.
return
}
// Close the connection if the context is cancelled.
log.Printf("[%d] new connection from %s\n",
connId, conn.RemoteAddr().String())
defer conn.Close()
go func() {
<-ctx.Done()
listener.Close()
}()
// Handle the connection with user provided handler.
ctx = context.WithValue(ctx, "connId", connId)
connId += 1
go func() {
// Handle any exception triggered by the user handler.
defer func() {
if (recover() != nil) {
log.Printf("[%d] triggered an exception", ctx.Value("connId"))
}
}()
handler(ctx, conn)
}()
}
}
func launchService(ctx context.Context, proto, addr string, handler ConnHandler) {
listener, err := net.Listen(proto, addr)
if err != nil {
panic(fmt.Sprintf("unable to bind on specified address: %v", err))
}
go handleConnections(ctx, listener, handler)
}