@@ -6,11 +6,14 @@ package proxy
6
6
7
7
import (
8
8
"bytes"
9
+ "context"
9
10
"crypto/tls"
11
+ "errors"
10
12
stdlog "log"
11
13
"net/http"
12
14
"os"
13
15
"path/filepath"
16
+ "time"
14
17
15
18
"github.com/gorilla/mux"
16
19
"github.com/klauspost/cpuid/v2"
@@ -49,13 +52,20 @@ func redirectToHTTPS(w http.ResponseWriter, r *http.Request) {
49
52
}
50
53
51
54
// MustServe starts the proxy and ends the process if doing so fails.
52
- func (p * WorkspaceProxy ) MustServe () {
55
+ func (p * WorkspaceProxy ) MustServe (ctx context. Context ) {
53
56
handler , err := p .Handler ()
54
57
if err != nil {
55
58
log .WithError (err ).Fatal ("cannot initialize proxy - this is likely a configuration issue" )
56
59
return
57
60
}
58
- srv := & http.Server {
61
+
62
+ httpServer := & http.Server {
63
+ Addr : p .Ingress .HTTPAddress ,
64
+ Handler : http .HandlerFunc (redirectToHTTPS ),
65
+ ErrorLog : stdlog .New (logrusErrorWriter {}, "" , 0 ),
66
+ }
67
+
68
+ httpsServer := & http.Server {
59
69
Addr : p .Ingress .HTTPSAddress ,
60
70
Handler : handler ,
61
71
TLSConfig : & tls.Config {
@@ -77,17 +87,35 @@ func (p *WorkspaceProxy) MustServe() {
77
87
crt = filepath .Join (tproot , crt )
78
88
key = filepath .Join (tproot , key )
79
89
}
90
+
80
91
go func () {
81
- err := http .ListenAndServe (p . Ingress . HTTPAddress , http . HandlerFunc ( redirectToHTTPS ) )
82
- if err != nil {
92
+ err := httpServer .ListenAndServe ()
93
+ if err != nil && ! errors . Is ( err , http . ErrServerClosed ) {
83
94
log .WithError (err ).Fatal ("cannot start http proxy" )
84
95
}
85
96
}()
86
97
87
- err = srv .ListenAndServeTLS (crt , key )
98
+ go func () {
99
+ err = httpsServer .ListenAndServeTLS (crt , key )
100
+ if err != nil && ! errors .Is (err , http .ErrServerClosed ) {
101
+ log .WithError (err ).Fatal ("cannot start proxy" )
102
+ return
103
+ }
104
+ }()
105
+
106
+ <- ctx .Done ()
107
+
108
+ shutDownCtx , cancel := context .WithTimeout (ctx , 5 * time .Minute )
109
+ defer cancel ()
110
+
111
+ err = httpServer .Shutdown (shutDownCtx )
88
112
if err != nil {
89
- log .WithError (err ).Fatal ("cannot start proxy" )
90
- return
113
+ log .WithError (err ).Fatal ("cannot stop HTTP server" )
114
+ }
115
+
116
+ err = httpsServer .Shutdown (shutDownCtx )
117
+ if err != nil {
118
+ log .WithError (err ).Fatal ("cannot stop HTTPS server" )
91
119
}
92
120
}
93
121
0 commit comments