-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapicaller.go
90 lines (69 loc) · 1.64 KB
/
apicaller.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
package sheetdb
import (
"bytes"
"context"
"encoding/json"
"errors"
"io"
"net/http"
"reflect"
)
// Call calls the API and returns the response.
type APICaller interface {
Call(
ctx context.Context,
method string,
url string,
opt Option,
body interface{},
response interface{},
) error
}
// APICallerImpl is an implementation of APICaller that uses an
// HTTP client to call the API.
type APICallerImpl struct {
HTTPClient *http.Client
}
func (a *APICallerImpl) Call(ctx context.Context, method string, url string, opt Option, body interface{}, response interface{}) error {
requestBody := []byte("")
var request *http.Request
var err error
isBodyNil := body == nil || (reflect.ValueOf(body).Kind() == reflect.Ptr && reflect.ValueOf(body).IsNil())
if !isBodyNil {
requestBody, err = json.Marshal(body)
if err != nil {
return err
}
}
request, err = http.NewRequestWithContext(
ctx,
method,
url,
bytes.NewBuffer(requestBody),
)
if err != nil {
return err
}
request.SetBasicAuth(opt.Username, opt.Password)
request.Header.Set("Content-Type", "application/json")
return a.do(request, response)
}
func (a *APICallerImpl) do(request *http.Request, response interface{}) error {
httpResponse, err := a.HTTPClient.Do(request)
if err != nil {
return err
}
defer httpResponse.Body.Close()
responseBody, err := io.ReadAll(httpResponse.Body)
if err != nil {
return err
}
if httpResponse.StatusCode < 200 || httpResponse.StatusCode > 299 {
err := errors.New("HTTP ERROR: " + string(responseBody))
return err
}
if err := json.Unmarshal(responseBody, &response); err != nil {
return err
}
return nil
}