-
Notifications
You must be signed in to change notification settings - Fork 0
/
request.go
85 lines (67 loc) · 1.59 KB
/
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
84
85
package cfdns
import (
"fmt"
"net/http"
"net/url"
"strings"
"golang.org/x/exp/maps"
)
type request struct {
method string
path string
queryParams url.Values
body any // the encoding/json package will be used to marshal it
}
type response[T any] struct {
body T
rawBody []byte
code int
headers http.Header
}
type HTTPError struct {
Code int
RawBody []byte
Headers http.Header
}
func (e HTTPError) Error() string {
msg := &strings.Builder{}
fmt.Fprintf(msg, "HTTP %d\n", e.Code)
headers := maps.Keys(e.Headers)
for _, k := range headers {
fmt.Fprintf(msg, "%s: %s\n", k, e.Headers.Get(k))
}
fmt.Fprintln(msg)
fmt.Fprintf(msg, "%s", e.RawBody)
return msg.String()
}
// IsPermanent returns true if should not try again the same request.
func (e HTTPError) IsPermanent() bool {
if e.Code >= 400 || e.Code < 500 {
return true
}
return false
}
var _ error = HTTPError{}
type CloudFlareError struct {
cfResponseCommon
HTTPError HTTPError
}
func (ce CloudFlareError) Error() string {
errs := make([]string, len(ce.Errors))
for i, err := range ce.Errors {
var chain []string
for _, ch := range err.ErrorChain {
chain = append(chain, fmt.Sprintf("%d %s", ch.Code, ch.Message))
}
chainmsg := ""
if len(chain) > 0 {
chainmsg = fmt.Sprintf(" (%s)", strings.Join(chain, "; "))
}
errs[i] = fmt.Sprintf("%d %s%s", err.Code, err.Message, chainmsg)
}
return fmt.Sprintf("CloudFlare error: %s\n\n%s", strings.Join(errs, ", "), ce.HTTPError.Error())
}
func (ce CloudFlareError) Unwrap() error {
return ce.HTTPError
}
var _ error = CloudFlareError{}