-
Notifications
You must be signed in to change notification settings - Fork 58
/
middlewares.go
179 lines (155 loc) · 4.35 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
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
package server
import (
"bufio"
"bytes"
"compress/gzip"
"encoding/json"
"fmt"
"io"
"net"
"net/http"
"runtime"
"time"
"github.com/Thiht/smocker/server/services"
"github.com/Thiht/smocker/server/types"
"github.com/labstack/echo/v4"
log "github.com/sirupsen/logrus"
)
type bodyDumpResponseWriter struct {
io.Writer
http.ResponseWriter
}
func (w *bodyDumpResponseWriter) WriteHeader(code int) {
w.ResponseWriter.WriteHeader(code)
}
func (w *bodyDumpResponseWriter) Write(b []byte) (int, error) {
return w.Writer.Write(b)
}
func (w *bodyDumpResponseWriter) Flush() {
w.ResponseWriter.(http.Flusher).Flush()
}
func (w *bodyDumpResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
return w.ResponseWriter.(http.Hijacker).Hijack()
}
func HistoryMiddleware(s services.Mocks) echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
session := s.GetLastSession()
if c.Request() == nil {
return echo.NewHTTPError(types.StatusSmockerInternalError, fmt.Sprintf("%s: Empty request", types.SmockerInternalError))
}
request := types.HTTPRequestToRequest(c.Request())
request.Date = time.Now()
responseBody := new(bytes.Buffer)
mw := io.MultiWriter(c.Response().Writer, responseBody)
writer := &bodyDumpResponseWriter{Writer: mw, ResponseWriter: c.Response().Writer}
c.Response().Writer = writer
if err := next(c); err != nil {
return echo.NewHTTPError(types.StatusSmockerInternalError, fmt.Sprintf("%s: %v", types.SmockerInternalError, err))
}
responseBytes := responseBody.Bytes()
if c.Response().Header().Get("Content-Encoding") == "gzip" {
r, err := gzip.NewReader(responseBody)
if err != nil {
log.WithError(err).Error("Unable to uncompress response body")
} else {
responseBytes, err = io.ReadAll(r)
if err != nil {
log.WithError(err).Error("Unable to read uncompressed response body")
responseBytes = responseBody.Bytes()
}
}
}
var body interface{}
if err := json.Unmarshal(responseBytes, &body); err != nil {
body = string(responseBytes)
}
context, _ := c.Get(types.ContextKey).(*types.Context)
if context == nil {
context = &types.Context{}
}
_, err := s.AddHistoryEntry(session.ID, &types.Entry{
Context: *context,
Request: request,
Response: types.Response{
Status: c.Response().Status,
Body: body,
Headers: c.Response().Header(),
Date: time.Now(),
},
})
if err != nil {
return echo.NewHTTPError(types.StatusSmockerInternalError, fmt.Sprintf("%s: %v", types.SmockerInternalError, err))
}
return nil
}
}
}
func loggerMiddleware() echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
req := c.Request()
start := time.Now()
p := req.URL.Path
if p == "" {
p = "/"
}
bytesIn := req.Header.Get(echo.HeaderContentLength)
if bytesIn == "" {
bytesIn = "0"
}
headers := fmt.Sprintf("%+v", req.Header)
entry := log.WithFields(log.Fields{
"start": start.Format(time.RFC3339),
"remote-ip": c.RealIP(),
"host": req.Host,
"uri": req.RequestURI,
"method": req.Method,
"path": p,
"headers": headers,
"bytes-in": bytesIn,
})
entry.Debug("Handling request...")
if err := next(c); err != nil {
c.Error(err)
}
res := c.Response()
end := time.Now()
entry = entry.WithFields(log.Fields{
"end": end.Format(time.RFC3339),
"status": res.Status,
"latency": end.Sub(start).String(),
"bytes-out": res.Size,
})
switch {
case res.Status < 400:
entry.Info("Handled request")
case res.Status < 500:
entry.Warn("Handled request")
default:
entry.Error("Handled request")
}
return nil
}
}
}
// Same as echo's RecoverWithConfig middleware, with DefaultRecoverConfig
func recoverMiddleware() echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
defer func() {
if r := recover(); r != nil {
err, ok := r.(error)
if !ok {
err = fmt.Errorf("%v", r)
}
stack := make([]byte, 4<<10) // 4 KB
length := runtime.Stack(stack, true)
log.WithError(err).Errorf("[PANIC RECOVER] %s", stack[:length])
c.Error(err)
}
}()
return next(c)
}
}
}