-
Notifications
You must be signed in to change notification settings - Fork 1
/
client.go
77 lines (60 loc) · 1.6 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
package swis
import (
"crypto/tls"
"encoding/json"
"fmt"
"net/http"
"net/url"
)
//Client swis proxy
type Client struct {
username string
password string
endpoint string
host string
}
type response struct {
Results []map[string]interface{} `json:"results"`
Message string `json:"message"`
}
// NewClient creates a new swis proxy
func NewClient(host, user, pass string, port int) *Client {
endpoint := fmt.Sprintf("https://%s:%d/SolarWinds/InformationService/v3/Json", host, port)
return &Client{
username: user,
password: pass,
endpoint: endpoint,
host: host,
}
}
// Query executes a swql query
func (p *Client) Query(query string) ([]map[string]interface{}, error) {
request := fmt.Sprintf("%s/Query?query=%s", p.endpoint, url.QueryEscape(query))
// create request
req, err := http.NewRequest("GET", request, nil)
if err != nil {
return nil, fmt.Errorf("new request failed: %v", err)
}
req.SetBasicAuth(p.username, p.password)
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
client := &http.Client{Transport: tr}
resp, err := client.Do(req)
if err != nil {
return nil, fmt.Errorf("request failed: %v", err)
}
if resp.StatusCode >= 400 {
return nil, fmt.Errorf("Query failed. Server returned: %v, ", resp.StatusCode)
}
defer resp.Body.Close()
var body response
err = json.NewDecoder(resp.Body).Decode(&body)
if err != nil {
return nil, fmt.Errorf("error unmarshalling body: %v", err)
}
if body.Message != "" {
return nil, fmt.Errorf("error executing query: %s", body.Message)
}
return body.Results, nil
}