-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.go
102 lines (81 loc) · 2.03 KB
/
api.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
package ya360
import (
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strings"
)
func (ya *Ya360) get(uri url.URL, resp interface{}) (int, error) {
u := ya.s.URL + uri.String()
// Create request
req, err := http.NewRequest(http.MethodGet, u, nil)
if err != nil {
return 0, fmt.Errorf("can't create new request: %v", err)
}
// Set Authorization header
req.Header.Add("Authorization", fmt.Sprintf("OAuth %s", ya.s.OAuth))
// Make request
res, err := http.DefaultClient.Do(req)
if err != nil {
return 0, err
}
defer res.Body.Close()
dJ := json.NewDecoder(res.Body)
e := errorRx{}
if res.StatusCode != http.StatusOK {
if err := dJ.Decode(&e); err != nil {
return res.StatusCode, err
}
return res.StatusCode, fmt.Errorf("wrong status code: %s", e.Message)
}
if resp != nil {
// Decode response
if err := dJ.Decode(&resp); err != nil {
return res.StatusCode, fmt.Errorf("can't decode response body: %v", err)
}
}
return res.StatusCode, nil
}
func (ya *Ya360) alter(method string, uri url.URL, req interface{}, resp interface{}) (int, error) {
var rdr io.Reader
u := ya.s.URL + uri.String()
if req != nil {
s, err := json.Marshal(req)
if err != nil {
return 0, err
}
rdr = strings.NewReader(string(s))
} else {
rdr = nil
}
r, err := http.NewRequest(method, u, rdr)
if err != nil {
return 0, err
}
// Set Authorization header
r.Header.Add("Content-Type", "application/json")
r.Header.Add("Authorization", fmt.Sprintf("OAuth %s", ya.s.OAuth))
// Make request
res, err := http.DefaultClient.Do(r)
if err != nil {
return 0, err
}
defer res.Body.Close()
dJ := json.NewDecoder(res.Body)
e := errorRx{}
if res.StatusCode != http.StatusOK {
if err := dJ.Decode(&e); err != nil {
return res.StatusCode, err
}
return res.StatusCode, fmt.Errorf("wrong status code: %s", e.Message)
}
if resp != nil {
// Decode response
if err := dJ.Decode(&resp); err != nil {
return res.StatusCode, fmt.Errorf("can't decode response body: %v", err)
}
}
return res.StatusCode, nil
}