Przeglądaj źródła

Basic Grafana client

Brendan Abolivier 6 lat temu
commit
04885adb2a
Podpisane przez: Brendan Abolivier <contact@brendanabolivier.com> ID klucza GPG: 8EF1500759F70623
3 zmienionych plików z 94 dodań i 0 usunięć
  1. 2
    0
      .gitignore
  2. 58
    0
      src/grafana/client.go
  3. 34
    0
      src/grafana/dashboards.go

+ 2
- 0
.gitignore Wyświetl plik

@@ -0,0 +1,2 @@
1
+bin
2
+pkg

+ 58
- 0
src/grafana/client.go Wyświetl plik

@@ -0,0 +1,58 @@
1
+package grafana
2
+
3
+import (
4
+	"bytes"
5
+	"fmt"
6
+	"io/ioutil"
7
+	"net/http"
8
+)
9
+
10
+type Client struct {
11
+	BaseURL    string
12
+	APIKey     string
13
+	httpClient *http.Client
14
+}
15
+
16
+func NewClient(baseURL string, apiKey string) (c *Client) {
17
+	return &Client{
18
+		BaseURL:    baseURL,
19
+		APIKey:     apiKey,
20
+		httpClient: new(http.Client),
21
+	}
22
+}
23
+
24
+func (c *Client) request(method string, endpoint string, body []byte) ([]byte, error) {
25
+	url := c.BaseURL + "/api/" + endpoint
26
+
27
+	req, err := http.NewRequest(method, url, bytes.NewBuffer(body))
28
+	if err != nil {
29
+		return nil, err
30
+	}
31
+
32
+	authHeader := fmt.Sprintf("Bearer %s", c.APIKey)
33
+	req.Header.Add("Authorization", authHeader)
34
+
35
+	resp, err := c.httpClient.Do(req)
36
+	if err != nil {
37
+		return nil, err
38
+	}
39
+
40
+	respBody, err := ioutil.ReadAll(resp.Body)
41
+	if err != nil {
42
+		return nil, err
43
+	}
44
+
45
+	if resp.StatusCode != http.StatusOK {
46
+		if resp.StatusCode == http.StatusNotFound {
47
+			err = fmt.Errorf("%s not found (404)", url)
48
+		} else {
49
+			err = fmt.Errorf(
50
+				"Unknown error: %d; body: %s",
51
+				resp.StatusCode,
52
+				string(respBody),
53
+			)
54
+		}
55
+	}
56
+
57
+	return respBody, err
58
+}

+ 34
- 0
src/grafana/dashboards.go Wyświetl plik

@@ -0,0 +1,34 @@
1
+package grafana
2
+
3
+import (
4
+	"encoding/json"
5
+)
6
+
7
+type dbSearchResponse struct {
8
+	ID      int      `json:"id"`
9
+	Title   string   `json:"title"`
10
+	URI     string   `json:"uri"`
11
+	Type    string   `json:"type"`
12
+	Tags    []string `json:"tags"`
13
+	Starred bool     `json:"isStarred"`
14
+}
15
+
16
+func (c *Client) GetDashboardsURIs() (URIs []string, err error) {
17
+	resp, err := c.request("GET", "search", nil)
18
+
19
+	var respBody []dbSearchResponse
20
+	if err = json.Unmarshal(resp, &respBody); err != nil {
21
+		return
22
+	}
23
+
24
+	URIs = make([]string, 0)
25
+	for _, db := range respBody {
26
+		URIs = append(URIs, db.URI)
27
+	}
28
+
29
+	return
30
+}
31
+
32
+func (c *Client) GetDashboardJSON(URI string) ([]byte, error) {
33
+	return c.request("GET", URI, nil)
34
+}