-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttp.go
76 lines (61 loc) · 1.51 KB
/
http.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
package hyper
import (
"context"
"errors"
"net/http"
)
const defaultAddress = ":8080"
var ErrMissingHandler = errors.New("missing http.Handler, pass it in the HTTP struct")
type HTTP struct {
TLS TLSDescriptor
TLSEnabled bool
Address string
Handler http.Handler
Log Logger
PreHooks []func(ctx context.Context)
PostHooks []func(ctx context.Context)
}
type Logger struct {
Infof infoLog
Errorf errorLog
}
type infoLog func(ctx context.Context, format string, args ...interface{})
type errorLog func(ctx context.Context, err error, format string, args ...interface{})
func (h HTTP) Serve(ctx context.Context, finisher chan error) {
if h.Address == "" {
h.Address = defaultAddress
}
if h.Handler == nil {
finisher <- ErrMissingHandler
return
}
srv := http.Server{
Addr: h.Address,
Handler: h.Handler,
}
if h.TLSEnabled {
var err error
srv.TLSConfig, err = h.TLS.from()
if err != nil {
finisher <- ErrMissingHandler
return
}
}
go h.shutdownListener(ctx, &srv, finisher)
if h.TLSEnabled {
h.Log.Infof(ctx, "HTTP server listening on %s with TLS", h.Address)
if err := srv.ListenAndServeTLS("", ""); err != nil {
finisher <- err
}
} else {
h.Log.Infof(ctx, "HTTP server listening on %s", h.Address)
if err := srv.ListenAndServe(); err != nil {
finisher <- err
}
}
}
func (h HTTP) shutdownListener(ctx context.Context, srv *http.Server, finisher chan error) {
<-ctx.Done()
h.Log.Infof(ctx, "graceful shutdown finished... exiting")
finisher <- srv.Shutdown(ctx)
}