-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserverctx.go
74 lines (69 loc) · 2.34 KB
/
serverctx.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
// Package serverctx provides net/http Server
// utilities for handling context cancellation signals.
package serverctx
import (
"context"
"net"
"net/http"
"time"
)
// Run calls ListenAndServeTLS on s
// and will gracefully shut it down
// when the given ctx is done. Any
// errors will be returned whether it's
// on startup or on shutdown.
func Run(ctx context.Context, s *http.Server, timeout time.Duration) error {
return RunTLS(ctx, s, timeout, "", "")
}
// RunTLS is like Run but calls ListenAndServeTLS instead.
func RunTLS(ctx context.Context, s *http.Server, timeout time.Duration, certFile, keyFile string) error {
serverErr := make(chan error, 1)
go func() {
// Capture ListenAndServe errors such as "port already in use".
// However, when a server is gracefully shutdown, it is safe to ignore errors
// returned from this method (given the select logic below), because
// Shutdown causes ListenAndServe to always return http.ErrServerClosed.
if certFile != "" && keyFile != "" {
serverErr <- s.ListenAndServeTLS(certFile, keyFile)
} else {
serverErr <- s.ListenAndServe()
}
}()
var err error
select {
case <-ctx.Done():
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
err = s.Shutdown(ctx)
case err = <-serverErr:
}
return err
}
// Serve is like Run but accepts a custom net.Listener to mimic net/http's Serve behavior.
func Serve(ctx context.Context, l net.Listener, s *http.Server, timeout time.Duration) error {
return ServeTLS(ctx, l, s, timeout, "", "")
}
// ServeTLS is like Serve but calls ServeTLS instead.
func ServeTLS(ctx context.Context, l net.Listener, s *http.Server, timeout time.Duration, certFile, keyFile string) error {
serverErr := make(chan error, 1)
go func() {
// Capture ListenAndServe errors such as "port already in use".
// However, when a server is gracefully shutdown, it is safe to ignore errors
// returned from this method (given the select logic below), because
// Shutdown causes ListenAndServe to always return http.ErrServerClosed.
if certFile != "" && keyFile != "" {
serverErr <- s.ServeTLS(l, certFile, keyFile)
} else {
serverErr <- s.Serve(l)
}
}()
var err error
select {
case <-ctx.Done():
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
err = s.Shutdown(ctx)
case err = <-serverErr:
}
return err
}