-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathprobe.go
More file actions
97 lines (72 loc) · 2.17 KB
/
probe.go
File metadata and controls
97 lines (72 loc) · 2.17 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
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
package main
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"github.com/valyala/fasthttp"
)
type FieldViolation struct {
Field string `json:"field"`
Description string `json:"description"`
}
type ErrorResponse struct {
Error struct {
Details []struct {
FieldViolations []FieldViolation `json:"fieldViolations"`
} `json:"details"`
} `json:"error"`
}
func testAPI(method, url string, headers map[string]string, payload []byte) (int, []byte, error) {
req := fasthttp.AcquireRequest()
defer fasthttp.ReleaseRequest(req)
req.SetRequestURI(url)
req.Header.SetMethod(method)
for k, v := range headers {
req.Header.Set(k, v)
}
req.Header.Set("Content-Type", "application/json+protobuf")
req.SetBody(payload)
resp := fasthttp.AcquireResponse()
defer fasthttp.ReleaseResponse(resp)
err := fasthttp.Do(req, resp)
if err != nil {
return 0, nil, err
}
return resp.StatusCode(), resp.Body(), err
}
func probeAPI(method, url string, headers map[string]string, payload []byte) ([]FieldViolation, error) {
req := fasthttp.AcquireRequest()
defer fasthttp.ReleaseRequest(req)
req.SetRequestURI(url)
req.Header.SetMethod(method)
for k, v := range headers {
req.Header.Set(k, v)
}
req.Header.Set("Content-Type", "application/json+protobuf")
req.SetBody(payload)
resp := fasthttp.AcquireResponse()
defer fasthttp.ReleaseResponse(resp)
err := fasthttp.Do(req, resp)
if err != nil {
return nil, err
}
var violations []FieldViolation
// Content-Type: application/json+protobuf (protojson)
if bytes.Contains(resp.Header.Peek("Content-Type"), []byte("application/json+protobuf")) {
return nil, errors.New("protojson parsing has not been implemented yet, try ?alt=json")
} else if bytes.Contains(resp.Header.Peek("Content-Type"), []byte("application/json")) {
var response ErrorResponse
err = json.Unmarshal(resp.Body(), &response)
if err != nil {
return nil, err
}
if response.Error.Details == nil {
return nil, nil
}
violations = response.Error.Details[0].FieldViolations
} else {
return nil, fmt.Errorf("%s parsing has not been implemented yet, try ?alt=json", string(resp.Header.Peek("Content-Type")))
}
return violations, nil
}