-
Notifications
You must be signed in to change notification settings - Fork 249
/
middleware.go
319 lines (299 loc) · 9.34 KB
/
middleware.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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
package rest
import (
"context"
"crypto/subtle"
"encoding/json"
"fmt"
"github.com/apolloconfig/agollo/v4/storage"
"github.com/ascarter/requestid"
"github.com/felixge/httpsnoop"
"github.com/klauspost/compress/gzip"
"github.com/opentracing-contrib/go-stdlib/nethttp"
"github.com/opentracing/opentracing-go"
"github.com/pkg/errors"
"github.com/slok/goresilience"
"github.com/slok/goresilience/bulkhead"
"github.com/uber/jaeger-client-go"
"github.com/unionj-cloud/go-doudou/v2/framework/configmgr"
"github.com/unionj-cloud/go-doudou/v2/framework/config"
"github.com/unionj-cloud/go-doudou/v2/toolkit/stringutils"
logger "github.com/unionj-cloud/go-doudou/v2/toolkit/zlogger"
"io"
"net/http"
"net/http/httptest"
"net/url"
"os"
"runtime/debug"
"strings"
"time"
)
var (
Tracing = tracing
Metrics = metrics
Log = log
BasicAuth = basicAuth
Recovery = recovery
)
type httpConfigListener struct {
configmgr.BaseApolloListener
}
func NewHttpConfigListener() *httpConfigListener {
return &httpConfigListener{}
}
func (c *httpConfigListener) OnChange(event *storage.ChangeEvent) {
c.Lock.Lock()
defer c.Lock.Unlock()
if !c.SkippedFirstEvent {
c.SkippedFirstEvent = true
return
}
for key, value := range event.Changes {
upperKey := strings.ToUpper(strings.ReplaceAll(key, ".", "_"))
if strings.HasPrefix(upperKey, "GDD_MANAGE_") {
_ = os.Setenv(upperKey, fmt.Sprint(value.NewValue))
}
}
}
func CallbackOnChange(listener *httpConfigListener) func(event *configmgr.NacosChangeEvent) {
return func(event *configmgr.NacosChangeEvent) {
changes := make(map[string]*storage.ConfigChange)
for k, v := range event.Changes {
changes[k] = &storage.ConfigChange{
OldValue: v.OldValue,
NewValue: v.NewValue,
ChangeType: storage.ConfigChangeType(v.ChangeType),
}
}
changeEvent := &storage.ChangeEvent{
Changes: changes,
}
listener.OnChange(changeEvent)
}
}
func InitialiseRemoteConfigListener() {
listener := &httpConfigListener{}
configType := config.GddConfigRemoteType.LoadOrDefault(config.DefaultGddConfigRemoteType)
switch configType {
case "":
return
case config.NacosConfigType:
dataIdStr := config.GddNacosConfigDataid.LoadOrDefault(config.DefaultGddNacosConfigDataid)
dataIds := strings.Split(dataIdStr, ",")
listener.SkippedFirstEvent = true
for _, dataId := range dataIds {
configmgr.NacosClient.AddChangeListener(configmgr.NacosConfigListenerParam{
DataId: "__" + dataId + "__" + "rest",
OnChange: CallbackOnChange(listener),
})
}
case config.ApolloConfigType:
configmgr.ApolloClient.AddChangeListener(listener)
default:
logger.Warn().Msgf("[go-doudou] unknown config type: %s\n", configType)
}
}
func init() {
InitialiseRemoteConfigListener()
}
// metrics logs some metrics for http request
func metrics(inner http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
m := httpsnoop.CaptureMetrics(inner, w, r)
logger.Info().
Msgf("%s\t%s\t%s\t%d\t%d\t%s", r.RemoteAddr,
r.Method,
r.URL,
m.Code,
m.Written,
m.Duration.String())
})
}
// log logs http request body and response body for debugging
func log(inner http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var (
reqBodyCopy io.ReadCloser
err error
traceId string
)
if reqBodyCopy, r.Body, err = CopyReqBody(r.Body); err != nil {
logger.Error().Err(err).Msg("call copyReqBody(r.Body) error")
}
rec := httptest.NewRecorder()
start := time.Now()
inner.ServeHTTP(rec, r)
elapsed := time.Since(start)
reqBody := GetReqBody(reqBodyCopy, r)
rid, _ := requestid.FromContext(r.Context())
span := opentracing.SpanFromContext(r.Context())
if jspan, ok := span.(*jaeger.Span); ok {
traceId = jspan.SpanContext().TraceID().String()
}
respBody := GetRespBody(rec)
reqQuery := r.URL.RawQuery
if unescape, err := url.QueryUnescape(reqQuery); err == nil {
reqQuery = unescape
}
fields := map[string]interface{}{
"remoteAddr": r.RemoteAddr,
"httpMethod": r.Method,
"requestUrl": r.URL.String(),
"proto": r.Proto,
"host": r.Host,
"reqContentLength": r.ContentLength,
"reqHeader": r.Header,
"requestId": rid,
"reqQuery": reqQuery,
"reqBody": reqBody,
"respBody": respBody,
"statusCode": rec.Result().StatusCode,
"respHeader": rec.Result().Header,
"respContentLength": rec.Body.Len(),
"elapsedTime": elapsed.String(),
"elapsed": elapsed.Milliseconds(),
"span": span,
"traceId": traceId,
}
var reqLog string
if reqLog, err = JsonMarshalIndent(fields, "", " ", true); err != nil {
reqLog = fmt.Sprintf("call jsonMarshalIndent(fields, \"\", \" \", true) error: %s", err)
}
logger.Info().Fields(fields).Msg(reqLog)
header := rec.Result().Header
for k, v := range header {
w.Header()[k] = v
}
w.WriteHeader(rec.Result().StatusCode)
rec.Body.WriteTo(w)
})
}
// rest set Content-Type to application/json
func rest(inner http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if stringutils.IsEmpty(w.Header().Get("Content-Type")) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
}
inner.ServeHTTP(w, r)
})
}
// basicAuth adds http basic auth validation
func basicAuth() func(inner http.Handler) http.Handler {
username := config.DefaultGddManageUser
password := config.DefaultGddManagePass
return func(inner http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if stringutils.IsNotEmpty(config.GddManageUser.Load()) {
username = config.GddManageUser.Load()
}
if stringutils.IsNotEmpty(config.GddManagePass.Load()) {
password = config.GddManagePass.Load()
}
user, pass, ok := r.BasicAuth()
if !ok || subtle.ConstantTimeCompare([]byte(user), []byte(username)) != 1 || subtle.ConstantTimeCompare([]byte(pass), []byte(password)) != 1 {
w.Header().Set("WWW-Authenticate", `Basic realm="Provide user name and password"`)
w.WriteHeader(401)
w.Write([]byte("Unauthorised.\n"))
return
}
inner.ServeHTTP(w, r)
})
}
}
// recovery handles panic from processing incoming http request
func recovery(inner http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
if e := recover(); e != nil {
statusCode := http.StatusInternalServerError
errCode := 1 // 1 indicates there is an error
message := fmt.Sprintf("%v", e)
if err, ok := e.(error); ok {
switch {
case errors.Is(err, context.Canceled):
statusCode = http.StatusBadRequest
default:
var bizError BizError
if errors.As(err, &bizError) {
statusCode = bizError.StatusCode
errCode = bizError.ErrCode
message = bizError.Error()
}
}
}
w.WriteHeader(statusCode)
if stringutils.IsEmpty(message) {
message = http.StatusText(statusCode)
}
logger.Error().Msgf("panic: %+v\n\nstacktrace from panic: %s\n", e, string(debug.Stack()))
if _err := json.NewEncoder(w).Encode(struct {
Code int `json:"code"`
Message string `json:"message"`
}{
Code: errCode,
Message: message,
}); _err != nil {
http.Error(w, _err.Error(), http.StatusInternalServerError)
return
}
}
}()
inner.ServeHTTP(w, r)
})
}
// gzipBody handles gzip-ed request body
func gzipBody(inner http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Handle gzip decoding of the body
if r.Header.Get("Content-Encoding") == "gzip" {
b, err := gzip.NewReader(r.Body)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
defer b.Close()
r.Body = b
}
inner.ServeHTTP(w, r)
})
}
// tracing add jaeger tracing middleware
func tracing(inner http.Handler) http.Handler {
return nethttp.Middleware(
opentracing.GlobalTracer(),
inner,
nethttp.OperationNameFunc(func(r *http.Request) string {
return fmt.Sprintf("HTTP %s: %s", r.Method, r.URL.Path)
}))
}
var RunnerChain = goresilience.RunnerChain
// BulkHead add bulk head pattern middleware based on https://github.com/slok/goresilience
// workers is the number of workers in the execution pool.
// maxWaitTime is the max time an incoming request will wait to execute before being dropped its execution and return 429 response.
func BulkHead(workers int, maxWaitTime time.Duration) func(inner http.Handler) http.Handler {
runner := RunnerChain(
bulkhead.NewMiddleware(bulkhead.Config{
Workers: workers,
MaxWaitTime: maxWaitTime,
}),
)
return func(inner http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
err := runner.Run(r.Context(), func(_ context.Context) error {
inner.ServeHTTP(w, r)
return nil
})
if err != nil {
http.Error(w, "too many requests", http.StatusTooManyRequests)
}
})
}
}
func BodyMaxBytes(n int64) func(inner http.Handler) http.Handler {
return func(inner http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
r2 := *r
r2.Body = http.MaxBytesReader(w, r.Body, n)
inner.ServeHTTP(w, &r2)
})
}
}