/
middleware.go
94 lines (88 loc) · 2.31 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
package httpserver
import (
"fmt"
"strconv"
"time"
"github.com/gin-gonic/gin"
"github.com/sabariramc/goserverbase/v5/instrumentation/span"
)
func (h *HTTPServer) SetContextMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
r := c.Request
corr := h.GetCorrelationParams(r)
identity := h.GetCustomerID(r)
ctx := h.GetContextWithCorrelation(r.Context(), corr)
ctx = h.GetContextWithCustomerId(ctx, identity)
c.Request = r.WithContext(ctx)
if h.tracer != nil {
span, ok := h.tracer.GetSpanFromContext(ctx)
if ok {
span.SetAttribute("correlationId", corr.CorrelationID)
defer span.Finish()
data := identity.GetPayload()
for key, value := range data {
if value != "" {
span.SetAttribute("user."+key, value)
}
}
}
}
c.Next()
}
}
func (h *HTTPServer) RequestTimerMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
r := c.Request
st := time.Now()
c.Next()
h.log.Info(r.Context(), "Request processing time in ms", time.Since(st).Milliseconds())
}
}
func (h *HTTPServer) LogRequestResponseMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
w, r := c.Writer, c.Request
ctx := r.Context()
r = r.WithContext(ctx)
req := h.GetMaskedRequestMeta(r)
c.Request = r
body, _ := h.CopyRequestBody(r)
logResWri := &loggingResponseWriter{
ResponseWriter: w,
ctx: r.Context(),
log: h.log,
reqBody: &body,
}
c.Writer = logResWri
h.log.Info(ctx, "Request", req)
h.log.Debug(ctx, "Request Body", func() string { return string(body) })
cs, spanOk := h.GetSpanFromContext(ctx)
defer func() {
if spanOk {
cs.SetAttribute(span.HTTPStatusCode, strconv.Itoa(logResWri.status))
}
}()
c.Next()
}
}
func (h *HTTPServer) PanicHandleMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
w, r := c.Writer, c.Request
ctx := r.Context()
span, spanOk := h.GetSpanFromContext(ctx)
defer func() {
if rec := recover(); rec != nil {
stackTrace, err := h.PanicRecovery(ctx, rec)
statusCode, body := h.ProcessError(ctx, stackTrace, err)
h.WriteJSONWithStatusCode(r.Context(), w, statusCode, body)
if spanOk {
err, errOk := rec.(error)
if !errOk {
err = fmt.Errorf("panic during execution")
}
span.SetError(err, stackTrace)
}
}
}()
c.Next()
}
}