-
Notifications
You must be signed in to change notification settings - Fork 2
/
client.go
100 lines (80 loc) · 1.62 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 salt
import (
"bytes"
"context"
"crypto/tls"
"encoding/json"
"io"
"net/http"
)
type Client struct {
Client *http.Client
Headers map[string]string
Server string
Token string
Events *Events
Jobs *Jobs
Keys *Keys
Minions *Minions
}
// New returns a new Client, initialized with the Salt API server.
func New(server string) *Client {
c := &Client{
Client: &http.Client{
Transport: &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: true,
},
},
},
Headers: map[string]string{
"Accept": "application/json",
"Content-Type": "application/json",
},
Server: server,
}
c.Events = &Events{c}
c.Jobs = &Jobs{c}
c.Keys = &Keys{c}
c.Minions = &Minions{c}
return c
}
type responseFunc func(*http.Response) error
func (c *Client) do(ctx context.Context, method, path string, data any, fn responseFunc) error {
var buf bytes.Buffer
if data != nil {
if err := json.NewEncoder(&buf).Encode(data); err != nil {
return err
}
}
req, err := http.NewRequestWithContext(ctx, method, c.Server+"/"+path, &buf)
if err != nil {
return err
}
for key, val := range c.Headers {
req.Header.Set(key, val)
}
if len(c.Token) > 0 {
req.Header.Set("X-Auth-Token", c.Token)
}
res, err := c.Client.Do(req)
if err != nil {
return err
}
// Discard any unread bytes, and close the response body.
defer func() {
io.Copy(io.Discard, res.Body)
res.Body.Close()
}()
var ok = map[int]bool{
200: true,
202: true,
}
if !ok[res.StatusCode] {
return NewError(res.StatusCode, htmlParagraph(res.Body))
}
if fn == nil {
return nil
}
return fn(res)
}