-
Notifications
You must be signed in to change notification settings - Fork 2
/
client.go
78 lines (61 loc) · 1.95 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
// Copyright(C) 2022 PingCAP. All Rights Reserved.
package main
import (
"encoding/json"
"fmt"
"net/http"
"sync"
"github.com/go-resty/resty/v2"
"github.com/icholy/digest"
)
var (
clientInitOnce sync.Once
restClient *resty.Client
)
func initClient(publicKey, privateKey string) error {
clientInitOnce.Do(func() {
restClient = resty.New()
restClient.SetTransport(&digest.Transport{
Username: publicKey,
Password: privateKey,
})
})
return nil
}
// doRequest wraps resty request, it's a generic method to spawn a HTTP request
func doRequest(method, url string, payload, output interface{}) (*resty.Response, error) {
request := restClient.R()
// if payload is not nil, we'll put it on body
if payload != nil {
request.SetBody(payload)
}
// execute the request
resp, err := request.Execute(method, url)
b, _ := json.Marshal(payload)
fmt.Printf("\npayload: %s\n", b)
fmt.Printf("\nRequest: method %s, url %s, response %s\n\n", method, url, resp)
if err != nil {
return nil, err
}
// if the request return a non-200 response, wrap it with error
if resp.StatusCode() != http.StatusOK {
return resp, fmt.Errorf("Failed with status %d and resp %s", resp.StatusCode(), resp)
}
// if we need to unmarshal the response into a struct, we pass it here, otherwise pass nil in the argument
if output != nil {
return resp, json.Unmarshal(resp.Body(), output)
}
return resp, nil
}
func doGET(url string, payload, output interface{}) (*resty.Response, error) {
return doRequest(resty.MethodGet, url, payload, output)
}
func doPOST(url string, payload, output interface{}) (*resty.Response, error) {
return doRequest(resty.MethodPost, url, payload, output)
}
func doDELETE(url string, payload, output interface{}) (*resty.Response, error) {
return doRequest(resty.MethodDelete, url, payload, output)
}
func doPATCH(url string, payload, output interface{}) (*resty.Response, error) {
return doRequest(resty.MethodPatch, url, payload, output)
}