/
middleware.go
199 lines (165 loc) · 5.19 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
// podium
// https://github.com/topfreegames/podium
// Licensed under the MIT license:
// http://www.opensource.org/licenses/mit-license
// Copyright © 2016 Top Free Games <backend@tfgco.com>
// Forked from
// https://github.com/dayvson/go-leaderboard
// Copyright © 2013 Maxwell Dayvson da Silva
package api
import (
"context"
"encoding/base64"
"fmt"
"net/http"
"runtime/debug"
"time"
"github.com/getsentry/raven-go"
"github.com/topfreegames/podium/log"
"go.uber.org/zap"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
grpc_auth "github.com/grpc-ecosystem/go-grpc-middleware/auth"
)
type newRelicContextKey struct {
key string
}
func (app *App) noAuthMiddleware(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
return handler(ctx, req)
}
func (app *App) basicAuthMiddleware(ctx context.Context) (context.Context, error) {
token, err := grpc_auth.AuthFromMD(ctx, "basic")
if err != nil {
return nil, err
}
auth := app.Config.GetString("basicauth.username") + ":" + app.Config.GetString("basicauth.password")
if token != base64.StdEncoding.EncodeToString([]byte(auth)) {
return nil, status.Errorf(codes.Unauthenticated, "invalid auth token")
}
return ctx, nil
}
func (app *App) loggerMiddleware(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
l := app.Logger.With(
zap.String("source", "request"),
)
//all except latency to string
var statusCode int
var latency time.Duration
var startTime, endTime time.Time
startTime = time.Now()
h, err := handler(ctx, req)
//no time.Since in order to format it well after
endTime = time.Now()
latency = endTime.Sub(startTime)
_, statusCode = app.getStatusCodeFromError(err)
method := info.FullMethod
reqLog := l.With(
zap.String("method", method),
zap.Time("endTime", endTime),
zap.Int("statusCode", statusCode),
zap.Duration("latency", latency),
)
//request failed
if statusCode > 399 && statusCode < 500 {
log.D(reqLog, "Request failed.")
return h, err
}
//request is ok, but server failed
if statusCode > 499 {
log.D(reqLog, "Response failed.")
return h, err
}
//Everything went ok
log.D(reqLog, "Request successful.")
return h, err
}
//Serve executes on error handler when errors happen
func (app *App) recoveryMiddleware(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
defer func() {
if err := recover(); err != nil {
eError, ok := err.(error)
if !ok {
eError = fmt.Errorf(fmt.Sprintf("%v", err))
}
app.OnErrorHandler(eError, debug.Stack())
}
}()
return handler(ctx, req)
}
func (app *App) responseTimeMetricsMiddleware(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
startTime := time.Now()
h, err := handler(ctx, req)
timeUsed := time.Since(startTime)
_, st := app.getStatusCodeFromError(err)
method := info.FullMethod
tags := []string{
fmt.Sprintf("method:%s", method),
fmt.Sprintf("status:%d", st),
}
if err := app.DDStatsD.Timing("response_time_milliseconds", timeUsed, tags...); err != nil {
app.Logger.Error("DDStatsD Timing", zap.Error(err))
}
return h, err
}
type addVersionMiddleware struct {
Handler http.Handler
}
func addVersionHeaders(w http.ResponseWriter) {
w.Header().Set("Server", fmt.Sprintf("Podium/v%s", VERSION))
w.Header().Set("Podium-Server", fmt.Sprintf("Podium/v%s", VERSION))
}
func (m addVersionMiddleware) ServeHTTP(w http.ResponseWriter, r *http.Request) {
addVersionHeaders(w)
m.Handler.ServeHTTP(w, r)
}
func addVersionHandlerFunc(f func(http.ResponseWriter, *http.Request)) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
addVersionHeaders(w)
f(w, r)
}
}
func (app *App) sentryMiddleware(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
h, err := handler(ctx, req)
if err != nil {
_, statusCode := app.getStatusCodeFromError(err)
if statusCode < 500 {
return h, err
}
tags := map[string]string{
"source": "app",
"type": "Internal server error",
"method": info.FullMethod,
"params": fmt.Sprintf("%v", req),
"status": fmt.Sprintf("%d", statusCode),
}
raven.CaptureError(err, tags)
}
return h, err
}
func (app *App) newRelicMiddleware(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
txn := app.NewRelic.StartTransaction(info.FullMethod, nil, nil)
newCtx := context.WithValue(ctx, newRelicContextKey{"txn"}, txn)
defer func() {
txn.End()
}()
h, err := handler(newCtx, req)
if err != nil {
txn.NoticeError(err)
}
return h, err
}
type removeTrailingSlashMiddleware struct {
Handler http.Handler
}
func (m *removeTrailingSlashMiddleware) removeTrailingSlash(path string) string {
l := len(path) - 1
if l > 0 && path != "/" && path[l] == '/' {
return path[:l]
}
return path
}
func (m removeTrailingSlashMiddleware) ServeHTTP(w http.ResponseWriter, r *http.Request) {
r.URL.Path = m.removeTrailingSlash(r.URL.Path)
m.Handler.ServeHTTP(w, r)
}