/
http.go
213 lines (182 loc) · 5.47 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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
/*
* Copyright (c) 2019 OysterPack, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package fxapp
import (
"context"
"errors"
"fmt"
"github.com/oysterpack/andiamo/pkg/eventlog"
"github.com/rs/zerolog"
"go.uber.org/fx"
"log"
"net/http"
"sort"
"sync"
"time"
)
// HTTPHandler is used to group HTTPEndpoint(s) together.
// The HTTPEndpoint(s) are automatically registered with the app's HTTP server.
type HTTPHandler struct {
fx.Out
HTTPEndpoint `group:"HTTPHandler"`
}
// NewHTTPHandler constructs a new HTTPHandler
func NewHTTPHandler(path string, handler func(http.ResponseWriter, *http.Request)) HTTPHandler {
return HTTPHandler{
HTTPEndpoint: HTTPEndpoint{
Path: path,
Handler: handler,
},
}
}
// HTTPEndpoint maps an HTTP handler to an HTTP path
type HTTPEndpoint struct {
Path string
Handler func(http.ResponseWriter, *http.Request)
}
// httpServerOpts is used by the app to configure and run an HTTP server only if HTTPEndpoint(s) are discovered, i.e.,
// registered with the app via dependency injection.
//
// An http.Server can be provided when building the app. If an http.Server is not found, then the app creates one with the
// following options:
// - Addr: ":8008",
// - ReadHeaderTimeout: time.Second,
// - MaxHeaderBytes: 1024,
type httpServerOpts struct {
fx.In
Server *http.Server `optional:"true"`
Endpoints []HTTPEndpoint `group:"HTTPHandler"`
}
// validate runs the following checks:
// - endpoint paths are unique
// - handler funcs are not nil
func (opts httpServerOpts) validate() error {
paths := make(map[string]bool, len(opts.Endpoints))
for _, endpoint := range opts.Endpoints {
if paths[endpoint.Path] {
return fmt.Errorf("duplicate HTTP endpoint path: %v", endpoint.Path)
}
if endpoint.Handler == nil {
return fmt.Errorf("http handler func is nil for: %v", endpoint.Path)
}
paths[endpoint.Path] = true
}
return nil
}
func (opts httpServerOpts) httpServerInfo() httpServerInfo {
endpoints := make([]string, 0, len(opts.Endpoints))
for _, endpoint := range opts.Endpoints {
endpoints = append(endpoints, endpoint.Path)
}
sort.Strings(endpoints)
return httpServerInfo{
addr: opts.Server.Addr,
endpoints: endpoints,
}
}
func runHTTPServer(opts httpServerOpts, logger *zerolog.Logger, lc fx.Lifecycle, readiness ReadinessWaitGroup) error {
if len(opts.Endpoints) == 0 {
// If there are no HTTP endpoints, then we don't need to run the HTTP server, but ...
//
// there should always be endpoints because the app registers endpoints for DevOps
// - Prometheus metrics
// - readiness probe
// - liveliness probe
// - healthchecks
//
// Thus if there are no endpoints, then a FATAL bug has been introduced
log.Fatal("FATAL: trying to run HTTP server with no handlers")
}
if err := opts.validate(); err != nil {
return err
}
readiness.Inc()
serveMux := http.NewServeMux()
for _, endpoint := range opts.Endpoints {
serveMux.HandleFunc(endpoint.Path, endpoint.Handler)
}
if opts.Server == nil {
opts.Server = newHTTPServerWithDefaultOpts()
}
opts.Server.Handler = serveMux
logHTTPServerErr := httpServerErrorLog(eventlog.NewLogger(HTTPServerError, logger, zerolog.ErrorLevel))
lc.Append(fx.Hook{
OnStart: func(context.Context) error {
eventlog.NewLogger(HTTPServerStarting, logger, zerolog.InfoLevel)(opts.httpServerInfo(), "starting HTTP server")
// wait for the HTTP server go routine to start running before returning
var wg sync.WaitGroup
wg.Add(1)
go func() {
wg.Done()
readiness.Done()
err := opts.Server.ListenAndServe()
if err != http.ErrServerClosed {
logHTTPServerErr(httpListenAndServerError{err}, "HTTP server has exited with an error")
}
}()
wg.Wait()
return nil
},
OnStop: func(ctx context.Context) error {
return opts.Server.Shutdown(ctx)
},
})
return nil
}
func newHTTPServerWithDefaultOpts() *http.Server {
return &http.Server{
Addr: ":8008",
ReadHeaderTimeout: time.Second,
MaxHeaderBytes: 1024,
}
}
// HTTP server related events
const (
// HTTPServerError indicates an error occurred while handling a metrics scrape HTTP request.
//
// type Data struct {
// Err string `json:"e"`
// }
HTTPServerError = "01DEDRH8A9X3SCSJRCJ4PM7749"
// type Data struct {
// Addr string
// Endpoints []string
// }
HTTPServerStarting = "01DEFM9FFSH58ZGNPSR7Z4C3G2"
)
type httpServerErrorLog eventlog.Logger
func (log httpServerErrorLog) Println(v ...interface{}) {
log(httpServerError(fmt.Sprint(v...)), "HTTP Server error")
}
type httpServerError string
func (err httpServerError) MarshalZerologObject(e *zerolog.Event) {
e.Err(errors.New(string(err)))
}
type httpListenAndServerError struct {
error
}
func (err httpListenAndServerError) MarshalZerologObject(e *zerolog.Event) {
e.Err(err)
}
type httpServerInfo struct {
addr string
endpoints []string
}
func (info httpServerInfo) MarshalZerologObject(e *zerolog.Event) {
e.
Str("addr", info.addr).
Strs("endpoints", info.endpoints)
}