-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddlewares.go
101 lines (96 loc) · 3.39 KB
/
middlewares.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
package rest
import (
"github.com/gozelus/zelus_rest/core/metric"
"github.com/gozelus/zelus_rest/logger"
"github.com/hashicorp/go-uuid"
"github.com/pkg/errors"
"strconv"
"time"
)
const serverNamespace = "http_server"
var (
metricServerReqDur = metric.NewHistogramVec(&metric.HistogramVecOpts{
Namespace: serverNamespace,
Subsystem: "requests",
Name: "duration_ms",
Help: "http server requests duration(ms).",
Labels: []string{"path"},
Buckets: []float64{5, 10, 25, 50, 100, 250, 500, 1000},
})
metricServerReqCodeTotal = metric.NewCounterVec(&metric.CounterVecOpts{
Namespace: serverNamespace,
Subsystem: "requests",
Name: "code_total",
Help: "http server requests error count.",
Labels: []string{"path", "code"},
})
)
var httpMetricsMiddleware = func(c Context) {
startTime := time.Now()
c.Next()
duration := time.Now().Sub(startTime).Milliseconds()
metricServerReqDur.Observe(int64(duration), c.Path())
metricServerReqCodeTotal.Inc(c.Path(), strconv.Itoa(c.HttpCode()))
}
var corsMiddleware = func(c Context) {
c.SetResponseHeader("Access-Control-Allow-Origin", "*")
c.SetResponseHeader("Access-Control-Allow-Credentials", "true")
c.SetResponseHeader("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
c.SetResponseHeader("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT")
if c.Method() == "OPTIONS" {
c.RenderOkJSON(nil)
return
}
c.Next()
}
var requestIdGenMiddleware = func(c Context) {
requestID, err := uuid.GenerateUUID()
if err != nil {
c.RenderErrorJSON(nil, err)
}
c.setRequestID(requestID)
}
var authorMiddleware = func(server *serverImp) func(HandlerFunc) HandlerFunc {
return func(handlerFunc HandlerFunc) HandlerFunc {
return func(ctx Context) {
if token, ok := ctx.Headers()["Authorization"]; ok && len(token) > 0 && len(token[0]) > 0 {
userID, newTokenStr, err := server.jwtUtils.ValidateToken(token[0])
if err != nil {
ctx.RenderErrorJSON(nil, statusUnauthorized)
return
}
ctx.setUserID(userID)
ctx.setJwtToken(newTokenStr)
handlerFunc(ctx)
return
}
ctx.RenderErrorJSON(nil, statusUnauthorized)
return
}
}
}
var recoverMiddleware = func(c Context) {
defer func() {
if err := recover(); err != nil {
logger.ErrorfWithStackWithContext(c, "recover err : %s", err)
c.RenderErrorJSON(nil, statusInternalServerError)
}
}()
c.Next()
}
var loggerMiddleware = func(c Context) {
now := time.Now()
logger.InfofWithContext(c, "query map : %v | json body : %s | headers : %v", c.QueryMap(), c.RequestBodyJsonStr(), c.Headers())
c.Next()
logger.InfofWithContext(c, "response body : %s", c.ResponseBodyJsonStr())
if err := c.GetError(); err != nil {
logger.WarnfWithContext(c, "bad request -> [%d] | method : %s | path : %s | duration : %d ms | err : %T -> %+v", c.HttpCode(), c.Method(), c.Path(), now.Sub(now).Milliseconds(), errors.Cause(err), err)
} else {
duration := time.Now().Sub(now).Milliseconds()
if duration > 300 {
logger.WarnfWithContext(c, "slow request -> [%d] | method : %s | path : %s | duration : %d ms", c.HttpCode(), c.Method(), c.Path(), time.Now().Sub(now).Milliseconds())
} else {
logger.InfofWithContext(c, "ok request -> [%d] | method : %s | path : %s | duration : %d ms", c.HttpCode(), c.Method(), c.Path(), time.Now().Sub(now).Milliseconds())
}
}
}