-
-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathrunner.go
114 lines (89 loc) · 1.77 KB
/
runner.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
103
104
105
106
107
108
109
110
111
112
113
114
package main
import (
"context"
"os"
"syscall"
"time"
"net/http"
"os/signal"
"golang.ngrok.com/ngrok"
)
type runner struct {
opt *options
ID string
tunnel ngrok.Tunnel
*os.File
*http.Server
}
func (r *runner) start(ctx context.Context) error {
if r.opt.Output != "" {
file, err := os.OpenFile(
r.opt.Output,
os.O_APPEND|os.O_CREATE|os.O_WRONLY,
0644,
)
if err != nil {
return err
}
r.File = file
httplog.Colors = false
httplog.SetOutput(file)
}
if !r.opt.Unstrip {
httplog.SkipHeader(skipHeaders)
}
tunnel, err := r.getTunnel()
if err != nil {
return err
}
authtoken, err := r.getAuthtokenOpt()
if err != nil {
return err
}
listener, err := ngrok.Listen(
ctx, tunnel, authtoken,
ngrok.WithDisconnectHandler(disconnected),
ngrok.WithConnectHandler(connected),
)
if err != nil {
return err
}
r.tunnel = listener
url, err := parseURL(listener.URL())
if err != nil {
return err
}
log.InfoContext(ctx,
"server started",
"url", url,
"id", listener.ID(),
)
r.ID = listener.ID()
handler := http.HandlerFunc(r.handler)
r.Server = &http.Server{Handler: handler}
sig := make(chan os.Signal, 1)
signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)
go func(ctx context.Context) {
if err := r.notify(sig); err != nil {
log.ErrorContext(ctx, err.Error())
os.Exit(1)
}
}(ctx)
return r.Serve(listener)
}
func (r *runner) end(sig os.Signal) error {
log.Warn("gracefully shutdown", "signal", sig)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
// log.Debug("closing tunnel")
err := r.tunnel.CloseWithContext(ctx)
if err != nil {
return err
}
// log.Debug("shutting down server")
err = r.Shutdown(ctx)
if err != nil {
return err
}
return nil
}