-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathquery.go
88 lines (77 loc) · 2.24 KB
/
query.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
package prometheus
import (
"encoding/json"
"io"
"net/http"
"net/url"
"strings"
)
// QueryResult - The result of a prometheus query and query_range request
// The Values field is used for both instant and range queries.
// For instant queries, the Values field will contain a single Value.
type QueryResult struct {
Metric map[string]string `json:"metric"`
Values []Value `json:"values"`
}
// UnmarshalJSON - Unmarshal the json response from prometheus
func (qr *QueryResult) UnmarshalJSON(data []byte) error {
type alias QueryResult
aux := struct {
*alias
Value Value `json:"value"`
}{
alias: (*alias)(qr),
}
if err := json.Unmarshal(data, &aux); err != nil {
return err
}
if !aux.Value.Timestamp.IsZero() {
qr.Values = append(qr.Values, aux.Value)
}
return nil
}
// QueryResponse - The return data from a simple prometheus time series query
type QueryResponse struct {
Status string `json:"status"`
Data struct {
ResultType string `json:"resultType"`
Result []QueryResult `json:"result"`
} `json:"data"`
}
// Query - fetch the data from prometheus API
func (c Client) Query(query Query) (*QueryResponse, error) {
query.values()
var path string
switch query.(type) {
case InstantQuery:
path = "api/v1/query"
case RangeQuery:
path = "api/v1/query_range"
}
request, requestCreateError := http.NewRequest(http.MethodPost, func(result string, _ error) string { return result }(url.JoinPath(c.Endpoint, path)), strings.NewReader(query.values().Encode()))
if requestCreateError != nil {
return nil, requestCreateError
}
// add custom headers
for key, value := range c.headers {
request.Header.Set(key, value)
}
request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
res, responseError := http.DefaultClient.Do(request)
if responseError != nil {
return nil, responseError
}
if res.StatusCode != http.StatusOK {
body, _ := io.ReadAll(res.Body)
return nil, ErrInvalidResponse{StatusCode: res.StatusCode, Message: string(body)}
}
var obj QueryResponse
if err := json.NewDecoder(res.Body).Decode(&obj); err != nil {
return nil, err
}
return &obj, nil
}
// Result - Only return the result struct of the query
func (obj *QueryResponse) Result() []QueryResult {
return obj.Data.Result
}