forked from nytm/go-grafana-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
63 lines (57 loc) · 1.21 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
package gapi
import (
"bytes"
"fmt"
"io"
"log"
"net/http"
"net/url"
"os"
"path"
"strings"
)
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 {
key = fmt.Sprintf("Bearer %s", auth)
}
return &Client{
key,
*u,
&http.Client{},
}, nil
}
func (c *Client) newRequest(method, requestPath string, body io.Reader) (*http.Request, error) {
url := c.baseURL
url.Path = path.Join(url.Path, requestPath)
req, err := http.NewRequest(method, url.String(), body)
if err != nil {
return req, err
}
if c.key != "" {
req.Header.Add("Authorization", c.key)
}
if os.Getenv("GF_LOG") != "" {
if body == nil {
log.Println("request to ", url.String(), "with no body data")
} else {
log.Println("request to ", url.String(), "with body data", body.(*bytes.Buffer).String())
}
}
req.Header.Add("Content-Type", "application/json")
return req, err
}