forked from content-services/content-sources-backend
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlog_server_error_request.go
83 lines (73 loc) · 1.71 KB
/
log_server_error_request.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
package middleware
import (
"bufio"
"errors"
"io"
"net/http"
ce "github.com/content-services/content-sources-backend/pkg/errors"
"github.com/labstack/echo/v4"
)
const BodyDumpLimit = 1000
const BodyStoreKey = "body_backup"
func LogServerErrorRequest(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) (err error) {
if c.Get(BodyStoreKey) == nil && isBodiedMethod(c.Request().Method) {
storeRequestBody(c)
}
if err = next(c); err != nil {
if containsServerError(err) && isBodiedMethod(c.Request().Method) {
logRequestBody(c)
}
return err
}
return nil
}
}
func containsServerError(err error) bool {
httpError := new(ce.ErrorResponse)
if errors.As(err, httpError) {
for _, e := range httpError.Errors {
if e.Status >= http.StatusInternalServerError {
return true
}
}
}
return false
}
func logRequestBody(c echo.Context) {
if body := c.Get(BodyStoreKey); body != nil {
storedBodyBytes, ok := body.([]byte)
if !ok {
c.Logger().Error("Error reading request body")
}
c.Logger().Errorf("Request body: %v", string(storedBodyBytes))
}
}
func storeRequestBody(c echo.Context) {
limit := BodyDumpLimit
buffered := BufferedReadCloser{bufio.NewReader(c.Request().Body), c.Request().Body}
bytes, err := buffered.Peek(BodyDumpLimit)
if errors.Is(err, io.EOF) {
limit = len(bytes)
err = nil
}
if errors.Is(err, bufio.ErrBufferFull) {
err = nil
}
if err != nil {
c.Logger().Error("Error reading request body")
return
}
c.Set(BodyStoreKey, bytes[:limit])
c.Request().Body = buffered
}
func isBodiedMethod(method string) bool {
switch method {
case http.MethodGet:
return false
case http.MethodDelete:
return false
default:
return true
}
}