forked from blockfrost/blockfrost-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutil.go
127 lines (115 loc) · 2.53 KB
/
util.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
package blockfrost
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"github.com/blockfrost/blockfrost-go/internal/version"
)
func handleAPIErrorResponse(res *http.Response) error {
var err error
switch res.StatusCode {
case 400:
br := BadRequest{}
if err = json.NewDecoder(res.Body).Decode(&br); err != nil {
return err
}
return &APIError{
Response: br,
}
case 403:
ua := UnauthorizedError{}
if err = json.NewDecoder(res.Body).Decode(&ua); err != nil {
return err
}
return &APIError{
Response: ua,
}
case 404:
nf := NotFound{}
if err = json.NewDecoder(res.Body).Decode(&nf); err != nil {
return err
}
return &APIError{
Response: nf,
}
case 429:
ol := OverusageLimit{}
if err = json.NewDecoder(res.Body).Decode(&ol); err != nil {
return err
}
return &APIError{
Response: ol,
}
case 418:
ab := AutoBanned{}
if err = json.NewDecoder(res.Body).Decode(&ab); err != nil {
return err
}
return &APIError{
Response: ab,
}
case 500:
ise := InternalServerError{}
if err = json.NewDecoder(res.Body).Decode(&ise); err != nil {
return err
}
return &APIError{
Response: ise,
}
default:
data, err := ioutil.ReadAll(res.Body)
if err != nil {
return err
}
return &APIError{
Response: string(data),
}
}
}
func formatParams(v url.Values, query APIQueryParams) url.Values {
if query.Count > 0 && query.Count <= 100 {
v.Add("count", fmt.Sprintf("%d", query.Count))
}
if query.Page > 0 {
v.Add("page", fmt.Sprintf("%d", query.Page))
}
if query.Order == "asc" || query.Order == "desc" {
v.Add("order", query.Order)
}
if query.From != "" {
v.Add("from", query.From)
}
if query.To != "" {
v.Add("to", query.To)
}
v.Encode()
return v
}
func (c *apiClient) handleRequest(req *http.Request) (res *http.Response, err error) {
req.Header.Add("project_id", c.projectId)
userAgent := fmt.Sprintf("%s/%s", "blockfrost-go", version.String())
req.Header.Set("User-Agent", userAgent)
res, err = c.client.Do(req)
if err != nil {
return
}
if res.StatusCode != http.StatusOK {
return res, handleAPIErrorResponse(res)
}
return res, nil
}
func (ip *ipfsClient) handleRequest(req *http.Request) (res *http.Response, err error) {
req.Header.Add("project_id", ip.projectId)
userAgent := fmt.Sprintf("%s/%s", "blockfrost-go", version.String())
req.Header.Set("User-Agent", userAgent)
res, err = ip.client.Do(req)
if err != nil {
return
}
if res.StatusCode != http.StatusOK {
return res, handleAPIErrorResponse(res)
}
return res, nil
}