-
Notifications
You must be signed in to change notification settings - Fork 8
/
client.go
105 lines (87 loc) · 1.98 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
101
102
103
104
105
package salt
import (
"bytes"
"context"
"crypto/tls"
"encoding/json"
"io"
"log"
"net/http"
"net/http/cookiejar"
"strings"
"time"
)
type Client struct {
httpClient *http.Client
endpoint string
token string
skipVerify bool
timeout time.Duration
username string
password string
eauth string
}
func NewClient(opts ...ClientOption) *Client {
c := &Client{
endpoint: "https://localhost:8000",
skipVerify: false,
timeout: 60,
username: "salt",
password: "salt",
eauth: "pam",
}
for _, o := range opts {
o(c)
}
jar, err := cookiejar.New(nil)
if err != nil {
log.Fatalf("Got error while creating cookie jar %s", err.Error())
}
tr := &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: c.skipVerify,
},
}
c.httpClient = &http.Client{Transport: tr, Jar: jar, Timeout: c.timeout * time.Second}
return c
}
func (c *Client) doRequest(ctx context.Context, method, uri string, data interface{}) ([]byte, error) {
url := strings.Join([]string{c.endpoint, uri}, "/")
var buf bytes.Buffer
if data != nil {
enc := json.NewEncoder(&buf)
enc.SetEscapeHTML(false)
err := enc.Encode(data)
if err != nil {
return nil, err
}
}
req, err := http.NewRequestWithContext(ctx, method, url, &buf)
if err != nil {
return nil, err
}
req.Header.Set("Accept", "application/json")
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-Requested-With", "XMLHttpRequest")
if c.token != "" {
req.Header.Set("X-Auth-Token", c.token)
}
resp, err := c.httpClient.Do(req)
if err != nil {
return nil, err
}
defer func() {
_ = resp.Body.Close()
}()
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
return respBody, nil
}
func (c *Client) get(ctx context.Context, uri string) ([]byte, error) {
return c.doRequest(ctx, "GET", uri, nil)
}
func (c *Client) post(ctx context.Context, uri string, data interface{}) ([]byte, error) {
return c.doRequest(ctx, "POST", uri, data)
}