-
Notifications
You must be signed in to change notification settings - Fork 148
/
tcp_example_test.go
75 lines (63 loc) · 1.31 KB
/
tcp_example_test.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
package tableflip_test
import (
"flag"
"fmt"
"log"
"os"
"os/signal"
"syscall"
"time"
"github.com/cloudflare/tableflip"
)
// This shows how to use the Upgrader
// with a listener based service.
func Example_tcpServer() {
var (
listenAddr = flag.String("listen", "localhost:8080", "`Address` to listen on")
pidFile = flag.String("pid-file", "", "`Path` to pid file")
)
flag.Parse()
log.SetPrefix(fmt.Sprintf("%d ", os.Getpid()))
upg, err := tableflip.New(tableflip.Options{
PIDFile: *pidFile,
})
if err != nil {
panic(err)
}
defer upg.Stop()
// Do an upgrade on SIGHUP
go func() {
sig := make(chan os.Signal, 1)
signal.Notify(sig, syscall.SIGHUP)
for range sig {
err := upg.Upgrade()
if err != nil {
log.Println("upgrade failed:", err)
}
}
}()
ln, err := upg.Fds.Listen("tcp", *listenAddr)
if err != nil {
log.Fatalln("Can't listen:", err)
}
go func() {
defer ln.Close()
log.Printf("listening on %s", ln.Addr())
for {
c, err := ln.Accept()
if err != nil {
return
}
go func() {
c.SetDeadline(time.Now().Add(time.Second))
c.Write([]byte("It is a mistake to think you can solve any major problems just with potatoes.\n"))
c.Close()
}()
}
}()
log.Printf("ready")
if err := upg.Ready(); err != nil {
panic(err)
}
<-upg.Exit()
}