-
Notifications
You must be signed in to change notification settings - Fork 32
/
main.go
102 lines (78 loc) · 1.73 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package main
import (
"context"
"flag"
"log"
"net/http"
"net/http/httputil"
"os"
"os/signal"
"sync"
"syscall"
"time"
)
var (
shutdownTimeout = time.Second * 3
defaultIdleTimeout = time.Second * 60
)
func main() {
addr := flag.String("http-addr", "127.0.0.1:7001", "listen addr for HTTP server")
flag.Parse()
ctx := context.Background()
proxyListenAddr := *addr
p := NewProxy()
wg := sync.WaitGroup{}
wg.Add(1)
ctx, s, err := StartProxy(ctx, proxyListenAddr, p)
if err != nil {
log.Println("unable to start proxy", err)
os.Exit(1)
}
wait(ctx, s)
}
// StartProxy starts a httputil.ReverseProxy listening on addr
func StartProxy(ctx context.Context, addr string, p *httputil.ReverseProxy) (context.Context, stopFunction, error) {
idleTimeout := defaultIdleTimeout
s := &http.Server{
Addr: addr,
Handler: p,
IdleTimeout: idleTimeout,
}
go func() {
var done func()
ctx, done = context.WithCancel(ctx)
log.Println("starting HTTP server", addr)
err := s.ListenAndServe()
if err != nil {
log.Println("listen and serve ended with error", err)
}
done()
}()
sf := func(ctx context.Context) error {
log.Println("shutting down server")
return s.Close()
}
return ctx, sf, nil
}
type stopFunction func(ctx context.Context) error
func wait(ctx context.Context, stoppers ...stopFunction) {
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
select {
case <-ctx.Done():
case <-c:
}
// call stop functions in reverse order
for i := len(stoppers) - 1; i >= 0; i-- {
s := stoppers[i]
if s == nil {
continue
}
ctx, done := context.WithTimeout(ctx, shutdownTimeout)
err := s(ctx)
if err != nil {
log.Println("did not exit", err)
}
done()
}
}