-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathis_json.go
More file actions
49 lines (44 loc) · 1.16 KB
/
is_json.go
File metadata and controls
49 lines (44 loc) · 1.16 KB
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
package main
import (
"bytes"
"encoding/json"
"io"
"mime"
"net/http"
"strings"
)
func isJson(reqAndResp *httpRequestAndResponse, maxContentLength int64) bool {
for _, headers := range []http.Header{reqAndResp.request.Header, reqAndResp.response.Header} {
contentTypeHeader := headers.Get("Content-Type")
mediaType, _, err := mime.ParseMediaType(contentTypeHeader)
if err == nil && mediaType == "application/json" {
return true
}
if strings.HasSuffix(mediaType, "+json") {
return true
}
}
if reqAndResp.request.ContentLength <= maxContentLength {
bodyBytes, err := io.ReadAll(reqAndResp.request.Body)
reqAndResp.request.Body = io.NopCloser(io.MultiReader(bytes.NewReader(bodyBytes)))
if err != nil {
return false
}
var v interface{}
if json.Unmarshal(bodyBytes, &v) == nil {
return true
}
}
if reqAndResp.response.ContentLength <= maxContentLength {
bodyBytes, err := io.ReadAll(reqAndResp.response.Body)
reqAndResp.response.Body = io.NopCloser(io.MultiReader(bytes.NewReader(bodyBytes)))
if err != nil {
return false
}
var v interface{}
if json.Unmarshal(bodyBytes, &v) == nil {
return true
}
}
return false
}