-
Notifications
You must be signed in to change notification settings - Fork 1
/
client.go
100 lines (78 loc) · 1.91 KB
/
client.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
package webdriver
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
)
type RestClient struct {
httpClient *http.Client
baseURL string
}
func NewRestClient(baseURL string) *RestClient {
return &RestClient{
httpClient: http.DefaultClient,
baseURL: baseURL,
}
}
type APIResponse struct {
Value json.RawMessage `json:"value"`
}
type APIError struct {
Error string `json:"error"`
Message string `json:"message"`
}
func (rc *RestClient) Do(req *http.Request) ([]byte, error) {
req.Header.Set("Accept", "application/json")
req.Header.Set("Accept-charset", "utf-8")
res, err := rc.httpClient.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
data, err := io.ReadAll(res.Body)
if err != nil {
return nil, err
}
response := &APIResponse{}
if err := json.Unmarshal(data, response); err != nil {
return nil, err
}
apiError := &APIError{}
if err := json.Unmarshal(response.Value, apiError); err == nil && apiError.Error != "" {
return nil, errors.New(apiError.Error)
}
return response.Value, nil
}
func (rc *RestClient) Get(path string) ([]byte, error) {
req, err := http.NewRequest(http.MethodGet, fmt.Sprintf("%s%s", rc.baseURL, path), nil)
if err != nil {
return nil, err
}
return rc.Do(req)
}
type Params map[string]interface{}
func (rc *RestClient) Post(path string, data *Params) ([]byte, error) {
if data == nil {
data = &Params{}
}
body, err := json.Marshal(data)
if err != nil {
return nil, err
}
req, err := http.NewRequest(http.MethodPost, fmt.Sprintf("%s%s", rc.baseURL, path), bytes.NewBuffer(body))
if err != nil {
return nil, err
}
req.Header.Add("Content-Type", "application/json;charset=utf-8")
return rc.Do(req)
}
func (rc *RestClient) Delete(path string) ([]byte, error) {
req, err := http.NewRequest(http.MethodDelete, fmt.Sprintf("%s%s", rc.baseURL, path), nil)
if err != nil {
return nil, err
}
return rc.Do(req)
}