forked from retzkek/go-grafana-api
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathclient.go
82 lines (75 loc) · 1.54 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
package gapi
import (
"bytes"
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"path"
"strings"
log "github.com/Sirupsen/logrus"
)
type Client struct {
key string
baseURL url.URL
*http.Client
}
//New creates a new grafana client
//auth can be in user:pass format, or it can be an api key
func New(auth, baseURL string) (*Client, error) {
u, err := url.Parse(baseURL)
if err != nil {
return nil, err
}
key := ""
if strings.Contains(auth, ":") {
split := strings.Split(auth, ":")
u.User = url.UserPassword(split[0], split[1])
} else if auth != "" {
key = fmt.Sprintf("Bearer %s", auth)
}
return &Client{
key,
*u,
&http.Client{},
}, nil
}
func (c *Client) newRequest(method, uri string, body io.Reader) (*http.Request, error) {
url := c.baseURL
url.Path = path.Join(url.Path, uri)
req, err := http.NewRequest(method, url.String(), body)
if err != nil {
return req, err
}
if c.key != "" {
req.Header.Add("Authorization", c.key)
}
if body == nil {
log.WithFields(log.Fields{
"url": url.String(),
}).Debug("request")
} else {
log.WithFields(log.Fields{
"url": url.String(),
"body": body.(*bytes.Buffer).String(),
}).Debug("request")
}
req.Header.Add("Content-Type", "application/json")
return req, err
}
func (c *Client) DoRead(req *http.Request) ([]byte, error) {
resp, err := c.Do(req)
if err != nil {
return nil, err
}
if resp.StatusCode != 200 {
return nil, errors.New(resp.Status)
}
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
return data, nil
}