-
Notifications
You must be signed in to change notification settings - Fork 14
/
http.go
192 lines (161 loc) · 6.36 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
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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
package core
import (
"context"
"crypto/tls"
"fmt"
"log"
"net/http"
"net/http/pprof"
"regexp"
"time"
"github.com/anz-bank/sysl-go/common"
"github.com/anz-bank/sysl-go/config"
"github.com/anz-bank/sysl-go/handlerinitialiser"
"github.com/anz-bank/sysl-go/metrics"
"github.com/anz-bank/sysl-go/status"
"github.com/go-chi/chi"
"github.com/prometheus/client_golang/prometheus"
"github.com/sirupsen/logrus"
)
type Manager interface {
EnabledHandlers() []handlerinitialiser.HandlerInitialiser
LibraryConfig() *config.LibraryConfig
AdminServerConfig() *config.CommonHTTPServerConfig
PublicServerConfig() *config.CommonHTTPServerConfig
}
type middlewareCollection struct {
admin []func(handler http.Handler) http.Handler
public []func(handler http.Handler) http.Handler
}
func configureAdminServerListener(hl Manager, logger *logrus.Logger, promRegistry *prometheus.Registry, mWare []func(handler http.Handler) http.Handler) (func() error, error) {
rootAdminRouter, adminRouter := configureRouters(hl.AdminServerConfig().BasePath, mWare)
adminTLSConfig, err := config.MakeTLSConfig(hl.AdminServerConfig().Common.TLS)
if err != nil {
return nil, err
}
// Define meta-service endpoints:
statusService := status.Service{
BuildMetadata: buildMetadata,
Config: hl.LibraryConfig(),
Services: hl.EnabledHandlers(),
}
adminRouter.Route("/-", func(r chi.Router) {
r.Route("/status", func(r chi.Router) {
status.WireRoutes(r, &statusService)
})
r.Route("/metrics", func(r chi.Router) {
r.Get("/", metrics.Handler(promRegistry).(http.HandlerFunc))
})
registerProfilingHandler(logger, hl.LibraryConfig(), r)
})
listenAdmin := prepareServerListener(logger, rootAdminRouter, adminTLSConfig, *hl.AdminServerConfig())
return listenAdmin, nil
}
func configurePublicServerListener(ctx context.Context, hl Manager, logger *logrus.Logger, mWare []func(handler http.Handler) http.Handler) (func() error, error) {
rootPublicRouter, publicRouter := configureRouters(hl.PublicServerConfig().BasePath, mWare)
publicTLSConfig, err := config.MakeTLSConfig(hl.PublicServerConfig().Common.TLS)
if err != nil {
return nil, err
}
for _, h := range hl.EnabledHandlers() {
h.WireRoutes(ctx, publicRouter)
}
if len(hl.EnabledHandlers()) == 0 {
logger.Warn("No service handlers enabled by config.")
}
listenPublic := prepareServerListener(logger, rootPublicRouter, publicTLSConfig, *hl.PublicServerConfig())
return listenPublic, nil
}
func registerProfilingHandler(logger *logrus.Logger, cfg *config.LibraryConfig, parentRouter chi.Router) {
if cfg.Profiling {
logger.Infoln("Register profiling handlers")
parentRouter.Group(func(r chi.Router) {
r.HandleFunc("/pprof", pprof.Index)
r.Handle("/allocs", pprof.Handler("allocs"))
r.Handle("/block", pprof.Handler("block"))
r.HandleFunc("/cmdline", pprof.Cmdline)
r.Handle("/goroutine", pprof.Handler("goroutine"))
r.Handle("/heap", pprof.Handler("heap"))
r.Handle("/mutex", pprof.Handler("mutex"))
r.HandleFunc("/profile", pprof.Profile)
r.Handle("/threadcreate", pprof.Handler("threadcreate"))
r.HandleFunc("/symbol", pprof.Symbol)
r.HandleFunc("/trace", pprof.Trace)
})
} else {
logger.Infoln("Skip register profiling handler due to profiling disabled")
}
}
func makeListenFunc(server *http.Server, logger *logrus.Logger, cfg config.CommonHTTPServerConfig) func() error {
return func() error {
if cfg.Common.TLS != nil {
logger.Infof("TLS configuration present. Preparing to serve HTTPS for address: %s:%d%s", cfg.Common.HostName, cfg.Common.Port, cfg.BasePath)
return server.ListenAndServeTLS("", "")
}
logger.Infof("no TLS configuration present. Preparing to serve HTTP for address: %s:%d%s", cfg.Common.HostName, cfg.Common.Port, cfg.BasePath)
return server.ListenAndServe()
}
}
func prepareServerListener(logger *logrus.Logger, rootRouter http.Handler, tlsConfig *tls.Config, httpConfig config.CommonHTTPServerConfig) func() error {
re := regexp.MustCompile(`TLS handshake error from .* EOF`) // Avoid spurious TLS errors from load balancer
writer := &TLSLogFilter{logger, re}
serverLogger := log.New(writer, "HTTPServer ", log.LstdFlags|log.Llongfile)
server := makeNewServer(rootRouter, tlsConfig, httpConfig, serverLogger)
listener := makeListenFunc(server, logger, httpConfig)
logger.Infof("configured listener for address: %s:%d%s", httpConfig.Common.HostName, httpConfig.Common.Port, httpConfig.BasePath)
return listener
}
func (m *middlewareCollection) addToBoth(h func(handler http.Handler) http.Handler) {
m.admin = append(m.admin, h)
m.public = append(m.public, h)
}
func prepareMiddleware(name string, logger *logrus.Logger, promRegistry *prometheus.Registry) middlewareCollection {
result := middlewareCollection{}
result.addToBoth(Recoverer(logger))
result.public = append(result.public, common.TraceabilityMiddleware(logger))
result.addToBoth(common.CoreRequestContextMiddleware(logger))
if promRegistry != nil {
metricsMiddleware := metrics.NewHTTPServerMetricsMiddleware(promRegistry, name, metrics.GetChiPathPattern)
result.addToBoth(metricsMiddleware)
}
return result
}
func makeNewServer(router http.Handler, tlsConfig *tls.Config, serverConfig config.CommonHTTPServerConfig, serverLogger *log.Logger) *http.Server {
listenAddr := fmt.Sprintf("%s:%d", serverConfig.Common.HostName, serverConfig.Common.Port)
return &http.Server{
Addr: listenAddr,
Handler: router,
TLSConfig: tlsConfig,
ReadTimeout: serverConfig.ReadTimeout,
WriteTimeout: serverConfig.WriteTimeout,
ReadHeaderTimeout: 10 * time.Second,
IdleTimeout: 5 * time.Second,
MaxHeaderBytes: http.DefaultMaxHeaderBytes,
ErrorLog: serverLogger,
}
}
func configureRouters(basePath string, mWare []func(handler http.Handler) http.Handler) (rootRouter, router *chi.Mux) {
rootRouter = chi.NewRouter()
rootRouter.Use(mWare...)
router = rootRouter.Route(basePath, nil).(*chi.Mux)
return rootRouter, router
}
// SelectBasePath chooses between a specified base path and a dynmaically chosen one
func SelectBasePath(fromSpec, dynamic string) string {
switch fromSpec {
case "": // fromSpec not specified
switch dynamic {
case "": // dynamic not specified
return "/"
default:
return dynamic
}
default: // fromSpec specified
switch dynamic {
case "": // dynamic not specified
return fromSpec
default:
return dynamic
}
}
}