-
Notifications
You must be signed in to change notification settings - Fork 33
/
Copy pathgindump.go
205 lines (178 loc) · 5.19 KB
/
gindump.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
200
201
202
203
204
205
package ginhelper
import (
"bytes"
"fmt"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/trace"
"io"
"mime"
"net/http"
"net/url"
"strings"
"github.com/gin-gonic/gin"
)
const traceName = "ginDump"
const dumpName = "http.dump"
// TraceMiddleware is a middleware that traces the request/response.
func TraceMiddleware(tracer trace.Tracer, printStr bool) gin.HandlerFunc {
return func(ctx *gin.Context) {
_, span := tracer.Start(ctx, traceName)
defer span.End()
// DumpWithOptions will call ctx.Next() to continue the request/response flow.
DumpWithOptions(true, true, true, true, true, func(dumpStr string) {
span.SetAttributes(attribute.String(dumpName, dumpStr))
if printStr {
fmt.Println(dumpStr)
}
})(ctx)
}
}
// Dump dumps the request and response.
func Dump() gin.HandlerFunc {
return DumpWithOptions(true, true, true, true, true, nil)
}
// DumpWithOptions dumps the request and response with options.
// nolint: gocognit, nestif, cyclop
func DumpWithOptions(showReq bool, showResp bool, showBody bool, showHeaders bool, showCookies bool, cb func(dumpStr string)) gin.HandlerFunc {
headerHiddenFields := make([]string, 0)
bodyHiddenFields := make([]string, 0)
if !showCookies {
headerHiddenFields = append(headerHiddenFields, "cookie")
}
return func(ctx *gin.Context) {
var strB strings.Builder
if showReq && showHeaders {
// dump req header
s, err := FormatToBeautifulJSON(ctx.Request.Header, headerHiddenFields)
if err != nil {
strB.WriteString(fmt.Sprintf("\nparse req header err \n" + err.Error()))
} else {
strB.WriteString("Request-Header:\n")
strB.Write(s)
}
}
if showReq && showBody {
// dump req body
// nolint: nestif
if ctx.Request.ContentLength > 0 {
buf, err := io.ReadAll(ctx.Request.Body)
if err != nil {
strB.WriteString(fmt.Sprintf("\nread bodyCache err \n %s", err.Error()))
goto DumpRes
}
rdr := io.NopCloser(bytes.NewBuffer(buf))
ctx.Request.Body = io.NopCloser(bytes.NewBuffer(buf))
ctGet := ctx.Request.Header.Get("Content-Type")
ct, _, err := mime.ParseMediaType(ctGet)
if err != nil {
strB.WriteString(fmt.Sprintf("\ncontent_type: %s parse err \n %s", ctGet, err.Error()))
goto DumpRes
}
switch ct {
case gin.MIMEJSON:
bts, err := io.ReadAll(rdr)
if err != nil {
strB.WriteString(fmt.Sprintf("\nread rdr err \n %s", err.Error()))
goto DumpRes
}
s, err := BeautifyJSONBytes(bts, bodyHiddenFields)
if err != nil {
strB.WriteString(fmt.Sprintf("\nparse req body err \n" + err.Error()))
goto DumpRes
}
strB.WriteString("\nRequest-Body:\n")
strB.Write(s)
case gin.MIMEPOSTForm:
bts, err := io.ReadAll(rdr)
if err != nil {
strB.WriteString(fmt.Sprintf("\nread rdr err \n %s", err.Error()))
goto DumpRes
}
val, err := url.ParseQuery(string(bts))
if err != nil {
strB.WriteString(fmt.Sprintf("\nparse query err \n" + err.Error()))
goto DumpRes
}
s, err := FormatToBeautifulJSON(val, bodyHiddenFields)
if err != nil {
strB.WriteString(fmt.Sprintf("\nparse req body err \n" + err.Error()))
goto DumpRes
}
strB.WriteString("\nRequest-Body:\n")
strB.Write(s)
case gin.MIMEMultipartPOSTForm:
default:
}
}
DumpRes:
ctx.Writer = &bodyWriter{bodyCache: bytes.NewBufferString(""), ResponseWriter: ctx.Writer}
ctx.Next()
}
if showResp && showHeaders {
// dump res header
sHeader, err := FormatToBeautifulJSON(ctx.Writer.Header(), headerHiddenFields)
if err != nil {
strB.WriteString(fmt.Sprintf("\nparse res header err \n" + err.Error()))
} else {
strB.WriteString("\nResponse-Header:\n")
strB.Write(sHeader)
}
}
if showResp && showBody {
bw, ok := ctx.Writer.(*bodyWriter)
if !ok {
strB.WriteString("\nbodyWriter was override , can not read bodyCache")
goto End
}
// dump res body
if bodyAllowedForStatus(ctx.Writer.Status()) && bw.bodyCache.Len() > 0 {
ctGet := ctx.Writer.Header().Get("Content-Type")
ct, _, err := mime.ParseMediaType(ctGet)
if err != nil {
strB.WriteString(fmt.Sprintf("\ncontent-type: %s parse err \n %s", ctGet, err.Error()))
goto End
}
switch ct {
case gin.MIMEJSON:
s, err := BeautifyJSONBytes(bw.bodyCache.Bytes(), bodyHiddenFields)
if err != nil {
strB.WriteString(fmt.Sprintf("\nparse bodyCache err \n" + err.Error()))
goto End
}
strB.WriteString("\nResponse-Body:\n")
strB.Write(s)
case gin.MIMEHTML:
default:
}
}
}
End:
if cb != nil {
cb(strB.String())
} else {
fmt.Println(strB.String())
}
}
}
type bodyWriter struct {
gin.ResponseWriter
bodyCache *bytes.Buffer
}
// rewrite Write().
func (w bodyWriter) Write(b []byte) (int, error) {
w.bodyCache.Write(b)
//nolint: wrapcheck
return w.ResponseWriter.Write(b)
}
// bodyAllowedForStatus is a copy of http.bodyAllowedForStatus non-exported function.
func bodyAllowedForStatus(status int) bool {
switch {
case status >= 100 && status <= 199:
return false
case status == http.StatusNoContent:
return false
case status == http.StatusNotModified:
return false
}
return true
}